【问题标题】:Binding Error Validation In Code and not in XAML在代码中而不是在 XAML 中绑定错误验证
【发布时间】:2019-03-04 00:03:05
【问题描述】:

我了解在XAML 中设置事件时如何绑定和处理验证错误,如下所示,我现在需要做的是添加相同的错误处理程序,但完全在没有XAML 的代码中添加控件在代码运行时。我已经搜索过,但找不到任何指向正确方向的东西。

<Grid>
    <TextBox Validation.Error="TextBox_Error" />
</Grid>

【问题讨论】:

标签: c# wpf xaml


【解决方案1】:

如果你没看错,这就是你要找的东西:

var element = yourRunTimeControl as DependencyObject;
System.Windows.Controls.Validation.AddErrorHandler(element, ErrorHandler)

private void ErrorHandler(object sender, System.Windows.Controls.ValidationErrorEventArgs e)
{
    ...
}

你可以阅读更多关于Validation.Error附加事件here

【讨论】:

    【解决方案2】:

    您还可以为控件设置 Binding 并为绑定添加 ValidationRules

                TextBox txtBox = new TextBox();
                txtBox.DataContext = // Your data;
    
                Binding binding = new Binding();
                binding.Path = // Set path;
                binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                binding.ValidatesOnDataErrors = true;
                binding.NotifyOnValidationError = true;
                binding.ValidationRules.Add(// Your ValidationRule class);
                txtBox.SetBinding(TextBox.TextProperty, binding);
    

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 2012-11-20
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多