在 WPF 中单击按钮时使用数据注释进行屏幕验证

Screen Validation With Data Annotations on Button Click in WPF

我有一个包含单个 属性“PersonName”的 WPF 表单。我想在 NULL OR EMPTY 上提出错误。我从 Data Annotations 得到了解决方案,我参考了教程 http://www.c-sharpcorner.com/uploadfile/20c06b/screen-validation-with-data-annotations-in-wpf/

我的XAML是

<TextBox Text="{Binding PersonName, UpdateSourceTrigger=PropertyChanged,
 NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />

<Button Content="Save" IsDefault="True" Command="{Binding SaveCommand}"
 IsEnabled="{Binding }" Width="150" Height="40"/>

我只能在 onPropertyChange 事件中看到错误。如果我直接点击按钮而不触及 TextBox 手段,我无法看到错误。我怎样才能在 Button Click.

上触发相同的功能

我的要求是PersonName不应该是NULL或者EMPTY,如果属性 是 NULLEMPTY,那么我需要禁用按钮,基于 IDataErrorInfo 不是 Property.Length

最初,我们不应用任何验证。一旦错误的数据输入或没有值点击按钮,那么我需要一个验证。

您可以将 ValidationRule 应用到您的 TextBox,如示例 here 然后在 Button

上设置触发器
<Button Content="Save" IsDefault="True" Command="{Binding SaveCommand} Width="150" Height="40">
    <Button.Style>
        <Style TargetType="Button">
          <Setter Property="IsEnabled" Value="False"/>
          <Style.Triggers>
            <MultiDataTrigger>
              <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding Path=(Validation.HasError), ElementName=PersonName}" Value="False"/>
              </MultiDataTrigger.Conditions>
              <Setter Property="IsEnabled" Value="True"/>
            </MultiDataTrigger>
            </Style.Triggers>
          </Style>
    </Button.Style>
</Button>

使用 IDataErrorInfo 接口并实现如下 luke

public class ABC : IDataErrorInfo
{
    private string _PersonName;
    public string PersonName
    {
        get { return _PersonName; }
        set
        {
            _PersonName = value;
            OnPropertyChanged("PersonName");
        }
    }

    public string Error
    {
        get { return string.Empty; }
    }

    public string this[string columnName]
    {
        get
        {
            if ("PersonName" == columnName)
            {
                if (String.IsNullOrEmpty(PersonName))
                {
                    return "Your Error Message";
                }
            }
        }
    }
}

并将 xaml 更改为

<TextBox Text="{Binding PersonName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}" />