Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将StackPane的可见性绑定到属性?_C#_Wpf_Mvvm_Data Binding_Visibility - Fatal编程技术网

C# 如何将StackPane的可见性绑定到属性?

C# 如何将StackPane的可见性绑定到属性?,c#,wpf,mvvm,data-binding,visibility,C#,Wpf,Mvvm,Data Binding,Visibility,我有几个堆栈窗格,我只想显示一个组合框的特定值。我已经让属性按我所希望的方式进行更改,但由于某些原因,当ComboBox值更新时,StackPane的可见性不会更新。不知道我做错了什么 RegisteredServersView.xaml <UserControl x:Class="WpfApp1.Servers.RegisteredServersView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presen

我有几个堆栈窗格,我只想显示一个组合框的特定值。我已经让属性按我所希望的方式进行更改,但由于某些原因,当ComboBox值更新时,StackPane的可见性不会更新。不知道我做错了什么

RegisteredServersView.xaml

<UserControl x:Class="WpfApp1.Servers.RegisteredServersView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp1.Servers"
        mc:Ignorable="d"
        Height="250" Width="600">

    <UserControl.DataContext>
        <local:RegisteredServersViewModel/>
    </UserControl.DataContext>

    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Server Instance:" Margin="30,10,10,10"/>
            <TextBox Text="{Binding ServerName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
                     Width="140" Margin="10">
                <Validation.ErrorTemplate>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <AdornedElementPlaceholder x:Name="textBox"/>
                            <TextBlock Margin="10" Text="{Binding [0].ErrorContent}" Foreground="Red"/>
                        </StackPanel>
                    </ControlTemplate>
                </Validation.ErrorTemplate>
            </TextBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Authorization Type:" Margin="10"/>
            <ComboBox Name="cbAuthType" 
                      Margin="10" 
                      ItemsSource="{Binding Types}"
                      SelectedItem="{Binding AuthType, UpdateSourceTrigger=PropertyChanged}" 
                      Width="141"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal"
                    Visibility="{Binding Vis}">
            <Label Content="Login:" Margin="80,10,10,10"/>
            <TextBox Text="{Binding Login, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
                     Width="140" Margin="10">
                <Validation.ErrorTemplate>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <AdornedElementPlaceholder x:Name="textBox"/>
                            <TextBlock Margin="10" Text="{Binding [0].ErrorContent}" Foreground="Red"/>
                        </StackPanel>
                    </ControlTemplate>
                </Validation.ErrorTemplate>
            </TextBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal"
                    Visibility="{Binding Vis}">
            <Label Content="Password:" Margin="60,10,10,10"/>
            <TextBox Text="{Binding Password, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
                     Width="140" Margin="10">
                <Validation.ErrorTemplate>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <AdornedElementPlaceholder x:Name="textBox"/>
                            <TextBlock Margin="10" Text="{Binding [0].ErrorContent}" Foreground="Red"/>
                        </StackPanel>
                    </ControlTemplate>
                </Validation.ErrorTemplate>
            </TextBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button x:Name="Reg"
                    Content="Register"
                    Click="OnSave"
                    Margin="145,10,10,10"
                    Width="60"
                    IsEnabled="{Binding ButtonEnabled, ValidatesOnDataErrors=True}"/>

            <Button x:Name="Cancel"
                    Content="Cancel"
                    Click="OnCancel"
                    Margin="5,10,10,10"
                    Width="60"/>
        </StackPanel>
    </StackPanel>
</UserControl>
RegisteredServersViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfApp1.Data;
using WpfApp1.Repos;
using System.Windows;

namespace WpfApp1.Servers
{
    public class RegisteredServersViewModel : INotifyPropertyChanged, IDataErrorInfo
    {
        private readonly RegisteredServerValidator _validator;
        private string _serverName;
        private string _authType;
        private string _login;
        private string _password;

        private Visibility _vis;

        public IEnumerable<string> _types;

        public RegisteredServersViewModel()
        {
            _types = new List<string>() { "SQLAuth", "Integrated" };
            _validator = new RegisteredServerValidator();
        }

        public IEnumerable<string> Types
        {
            get { return _types; }
        }

        public string ServerName
        {
            get { return _serverName; }
            set
            {
                _serverName = value;
                CheckButtonEnabled();
                OnPropertyChanged("ServerName");
            }
        }

        public string AuthType
        {
            get { return _authType; }
            set
            {
                _authType = value;

                if(value.Equals("SQLAuth"))
                {
                    Vis = Visibility.Visible;
                }
                else
                {
                    Vis = Visibility.Hidden;
                }

                CheckButtonEnabled();
                OnPropertyChanged("AuthType");
            }
        }


        public Visibility Vis
        {
            get { return _vis; }
            private set
            { 
                _vis = value;
                Console.WriteLine(_vis);
                OnPropertyChanged("Vis");
            }
        }

        public string Login
        {
            get { return _login; }
            set
            {
                _login = value;
                CheckButtonEnabled();
                OnPropertyChanged("Login");
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                CheckButtonEnabled();
                OnPropertyChanged("Password");
            }
        }

        public string this[string columnName]
        {
            get
            {
                var firstOrDefault = _validator.Validate(this).Errors.FirstOrDefault(lol => lol.PropertyName == columnName);
                if(firstOrDefault != null)
                {
                    return _validator != null ? firstOrDefault.ErrorMessage : "";
                }
                return "";
            }
        }

        public string Error
        {
            get
            {
                if(_validator != null)
                {
                    var results = _validator.Validate(this);
                    if(results != null && results.Errors.Any())
                    {
                        var errors = string.Join(Environment.NewLine, results.Errors.Select(x => x.ErrorMessage).ToArray());
                        return errors;
                    }
                }
                return string.Empty;
            }
        }

        private bool _buttonEnabled;

        public bool ButtonEnabled
        {
            get { return _buttonEnabled; }
            set
            {
                _buttonEnabled = value;
                //Console.WriteLine(_buttonEnabled);
                OnPropertyChanged("ButtonEnabled");
            }
        }

        public void CheckButtonEnabled()
        {
            if(ServerName != null && AuthType.Equals("SQLAuth") && Login != null && Password != null)
            {
                ButtonEnabled = true;
            }
            else if(ServerName != null && !AuthType.Equals("SQLAuth"))
            {
                ButtonEnabled = true;
            }
            else
            {
                ButtonEnabled = false;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用System.Windows.Input;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用WpfApp1.Data;
使用WpfApp1.Repos;
使用System.Windows;
命名空间WpfApp1.Servers
{
公共类RegisteredServerSiewModel:INotifyPropertyChanged,IDataErrorInfo
{
私有只读注册服务器验证程序_验证程序;
私有字符串_serverName;
私有字符串_authType;
私有字符串\u登录;
私有字符串\u密码;
私人能见度;
公共IEnumerable类型;
公共注册服务器IEWModel()
{
_types=newlist(){“SQLAuth”,“Integrated”};
_validator=新的RegisteredServerValidator();
}
公共IEnumerable类型
{
获取{return\u types;}
}
公共字符串服务器名
{
获取{return\u serverName;}
设置
{
_serverName=value;
CheckButtonEnabled();
OnPropertyChanged(“服务器名”);
}
}
公共字符串身份验证类型
{
获取{return\u authType;}
设置
{
_authType=值;
if(value.Equals(“SQLAuth”))
{
Vis=可见度。可见;
}
其他的
{
Vis=可见性。隐藏;
}
CheckButtonEnabled();
OnPropertyChanged(“AuthType”);
}
}
公众能见度
{
获取{return\u vis;}
专用设备
{ 
_vis=价值;
控制台写入线(_-vis);
不动产变更(“Vis”);
}
}
公共字符串登录
{
获取{return\u login;}
设置
{
_登录=值;
CheckButtonEnabled();
OnPropertyChanged(“登录”);
}
}
公共字符串密码
{
获取{return\u password;}
设置
{
_密码=值;
CheckButtonEnabled();
OnPropertyChanged(“密码”);
}
}
公共字符串此[string columnName]
{
得到
{
var firstOrDefault=\u validator.Validate(this).Errors.firstOrDefault(lol=>lol.PropertyName==columnName);
if(firstOrDefault!=null)
{
返回_validator!=null?firstOrDefault.ErrorMessage:;
}
返回“”;
}
}
公共字符串错误
{
得到
{
if(_validator!=null)
{
var results=\u validator.Validate(此);
if(results!=null&&results.Errors.Any())
{
var errors=string.Join(Environment.NewLine,results.errors.Select(x=>x.ErrorMessage.ToArray());
返回错误;
}
}
返回字符串。空;
}
}
已启用私有布尔(U)按钮;
公共布尔按钮已启用
{
获取{return\u buttonEnabled;}
设置
{
_按钮启用=值;
//控制台写入线(_按钮已启用);
关于财产变更(“按钮启用”);
}
}
public void CheckButtonEnabled()
{
if(ServerName!=null&&AuthType.Equals(“SQLAuth”)&&Login!=null&&Password!=null)
{
ButtonneEnabled=真;
}
else if(ServerName!=null&&!AuthType.Equals(“SQLAuth”))
{
ButtonneEnabled=真;
}
其他的
{
ButtonneEnabled=错误;
}
}
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void OnPropertyChanged(字符串propertyName)
{
PropertyChangedEventHandler处理程序=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
}
}
RegisteredServerValidator.cs

using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfApp1.Data;
using WpfApp1.Servers;

namespace WpfApp1
{
    class RegisteredServerValidator : AbstractValidator<RegisteredServersViewModel>
    {
        public RegisteredServerValidator()
        {
            RuleFor(instance => instance.ServerName)
                .NotEmpty()
                .WithMessage("This field cannot be left blank.");

            RuleFor(instance => instance.Login)
                .NotEmpty()
                .WithMessage("This field cannot be left blank.");

            RuleFor(instance => instance.Password)
                .NotEmpty()
                .WithMessage("This field cannot be left blank");
        }
    }
}

使用FluentValidation;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用WpfApp1.Data;
使用WpfApp1.Servers;
命名空间WpfApp1
{
类RegisteredServerValidator:AbstractValidator
{
公共注册服务器验证程序()
{
RuleFor(实例=>instance.ServerName)
.NotEmpty()
.WithMessage(“此字段不能为空”);
RuleFor(实例=>instance.Login)
.NotEmpty()
.WithMessage(“此字段不能为空”);
RuleFor(实例=>instance.Password)
.NotEmpty()
.WithMessage(“此字段不能为空”);
}
}
}
INotifyPropertyChanged.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class INotifyPropertyChanged : System.ComponentModel.INotifyPropertyChanged
    {
        protected virtual void SetProperty<T>(ref T member, T val,
            [CallerMemberName]string propertyName = null)
        {
            if (object.Equals(member, val)) return;
            member = val;
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用System.Linq;
使用System.Runtime.CompilerServices;
使用系统文本;
使用System.Threading.Tasks;
命名空间WpfApp1
{
已更改的公共类INotifyPropertyChanged:System.ComponentModel.INotifyPropertyChange
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class INotifyPropertyChanged : System.ComponentModel.INotifyPropertyChanged
    {
        protected virtual void SetProperty<T>(ref T member, T val,
            [CallerMemberName]string propertyName = null)
        {
            if (object.Equals(member, val)) return;
            member = val;
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
}
<Window x:Class="WpfApp1.Servers.RegisteredServersWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WpfApp1.Servers"
      mc:Ignorable="d" 
      Height="300" Width="500"
      Title="Registered Servers">

    <!--This contains the UserControl with the form.-->
    <Grid>
        <local:RegisteredServersView HorizontalAlignment="Left"
                                     Margin="0, 0, 0, 0"
                                     VerticalAlignment="Top"/>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1.Servers
{
    /// <summary>
    /// Interaction logic for RegisteredServersWindow.xaml
    /// </summary>
    public partial class RegisteredServersWindow : Window
    {
        public RegisteredServersWindow()
        {
            InitializeComponent();
        }
    }
}