在代码中而不在XAML中的绑定错误验证

时间:2018-09-28 03:06:47

标签: c# wpf xaml

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

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

2 个答案:

答案 0 :(得分:0)

如果理解正确,这就是您要寻找的东西:

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的更多信息。

答案 1 :(得分:0)

您还可以为控件设置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);