c# - MVVM CanExecute 返回 false 并且 Button 保持禁用状态

标签 c# wpf xaml

XAML:

     <TextBox x:Name="User" Text="{Binding Username}" Margin="0,0,62,0">
   <TextBox x:Name="Pass" Text="{Binding Password}"  Margin="0,0,62,0">
 <Button Command="{Binding Path= SaveCommand}"  IsDefault="True" Margin="10,0,1,9" Height="42" VerticalAlignment="Bottom">

如果我删除按钮上的绑定(bind)路径,按钮将再次启用。

View 模型:

  public class XViewModel : INotifyPropertyChanged
{
    private string _username;
    private string _password;


    public XViewModel()
    {
        SaveCommand = new DelegateCommand(Save, () => CanSave);

    }

    public string Username
    {
        get { return _username; }
        set
        {
            _username = value;
            NotifyOfPropertyChange("Username");
        }
    }
    public string Password
    {
        get { return _password; }
        set
        {
            _password = value;
            NotifyOfPropertyChange("Password");
        }
    }

    protected void NotifyOfPropertyChange(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    public ICommand SaveCommand { get; private set; }


    public bool CanSave
    {
        get { return !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public async void Save()
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StringConnexion"].ConnectionString);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "INSERT INTO Users(Login,password)VALUES(@Username,@Password)";
        cmd.Parameters.AddWithValue("@ID", Username);
        cmd.Parameters.AddWithValue("@FirstName", Password);

        try
        {
          await  con.OpenAsync();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }

        var sampleMessageDialog1 = new SampleMessageDialog
        {
            Message = { Text = "Connected" }
        };


           await DialogHost.Show(sampleMessageDialog1, "RootDialog");

    }

    public class DelegateCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public DelegateCommand(Action execute)
            : this(execute, () => true)
        {
            _execute = execute;
        }

        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {

            _execute();
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute();
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}

我以为它被禁用了,因为一开始没有在 TExtboxes 上写任何东西,但显然事实并非如此。 我基本上使用 https://www.codeproject.com/Articles/694908/Connecting-to-SQL-Server-using-MVVM-Pattern有一些变化。

编辑:

如果我用 DataContext 这样做:

  <Button Command="{Binding Path= SaveCommand}"  Margin="10,0,1,9" Height="42" Grid.Column="1" Grid.Row="3" VerticalAlignment="Bottom">
                <Button.DataContext>
                    <local:ConnexionViewModel Password="something" Username="sdfsdf" />
                </Button.DataContext>

按钮将被启用,somethingsdfsdf 将被添加到数据库中,但同样,这不是我想要的行为,我希望用户能够通过文本框输入登录名和密码。

最佳答案

当失去对 TextBox 的焦点时,TextBox 的 Text 属性会更新。如果在文本框中键入内容后焦点从文本框中丢失,则将启用“保存”按钮。如果您希望在您键入文本属性时立即更新它们,则需要将 Binding.UpdateSourceTrigger 属性设置为 PropertyChanged。

<TextBox x:Name="User" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,62,0"/>
<TextBox x:Name="Pass" Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}"  Margin="0,0,62,0"/>
<Button Command="{Binding Path= SaveCommand}"  Content="Save" IsDefault="True" Margin="10,0,1,9" Height="42" VerticalAlignment="Bottom"/>

关于c# - MVVM CanExecute 返回 false 并且 Button 保持禁用状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964229/

相关文章:

wpf - x :Reference and ElementName? 和有什么区别

WPF MVVM View /用户控件继承或类似概念?

c# - DataGridViewComboBoxColumn - 必须单击单元格两次才能显示组合框

c# - FindByThumbprint - 证书存在但未找到

wpf - MVVM - WPF : Updating view model boolean property when TextBox is being edited

asp.net - Windows Phone 应用程序在没有 Internet 连接的情况下与 wcf 服务通信时崩溃

c# - WPF:在 XP 上有 xamlparse 异常但在 Vista 上没有的任何原因?

.net - 如何生成一个与主机名不同的.EXE?

c# - Autofac - 注入(inject) UmbracoContext.ContentCache

c# - 将此上传图像应用程序转换为 MVC 架构