【问题标题】:WPF How to disable a button if validation on TextBox fails如果对 TextBox 的验证失败,WPF 如何禁用按钮
【发布时间】:2016-03-23 11:27:40
【问题描述】:

我有一个包含年龄的 TextBox 表单。我已经实现了这样的验证:

在我的 ViewModel 中,我有财产年龄:

private float age;

public float Age {
    get { return age; }
    set
   {
        if (value <= 0 || value > 120)
        {
            throw new ArgumentException("The age must be between 0 and 120 years");
        }
        age= value;
    } 
} 

我的 XAML 是:

<TextBox Name="txtAge" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, StringFormat=N1, ValidatesOnExceptions=True}" />

这一切都很好,如果我输入年龄 300,我的文本框下会显示错误。但是如果发生错误,我该如何禁用按钮呢?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    如果您使用的是 MVVM,那么您可以禁用 ICommand 的 CanExecute 中的按钮

    public ICommand RemoveCommand
    {
        get
        {
            if (this.removeCommand == null)
            {
                this.removeCommand = new RelayCommand<object>(this.ExecuteRemoveCommand, this.CanExecuteRemoveCommand);
            }
    
            return this.removeCommand;
        }
    }
    
    private void ExecuteRemoveCommand(object obj)
     {
    
     }    
    
    private bool CanExecuteRemoveCommand(object obj)
       {
         if (Age <= 0 || Age > 120)
           {
              return false;
           }    
              return true;
        }
    

    【讨论】:

      【解决方案2】:

      您是否在使用某种 MVVM 模式?你应该。我假设你是,因为你称它为 ViewModel。

      向 ViewModel 添加一个布尔属性。将其命名为 ButtonEnabled(使用比这更好的名称)。确保正确使用 INotifyPropertyChanged.PropertyChanged 事件。

      在 OneWay 绑定中将 Button 的 IsEnabled 属性绑定到 ViewModel 的 ButtonEnabled 属性。

      您可以选择如何设置 ButtonEnabled。

      1. 在 ButtonEnabled 属性 getter 中,如果 Age 属性值在正确的范围内,则返回 true,否则返回 false。

      -或-

      1. 在 Age 属性设置器中,设置或清除 ButtonEnabled 属性,具体取决于值是否在正确的范围内。

      【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2015-01-11
      • 1970-01-01
      相关资源
      最近更新 更多