【问题标题】:How to force update of validation error indicator (red line)如何强制更新验证错误指示器(红线)
【发布时间】:2018-01-30 10:34:30
【问题描述】:

App.xaml.cs 中,我注册了一个验证错误事件处理程序,以在发生验证错误时将我的所有TextBox 控件恢复为以前的值(VM 属性中的值)(例如,如果TextBox 绑定到双精度属性被输入一个字符串值)。

public App()
{
    EventManager.RegisterClassHandler(typeof(TextBox), Validation.ErrorEvent,
        new RoutedEventHandler(TextBox_ValidationErrorEventHandler));
}

private void TextBox_ValidationErrorEventHandler(object sender, RoutedEventArgs e)
{
    var tb = (TextBox)sender;
    DependencyProperty prop = TextBox.TextProperty;
    BindingExpression binding = BindingOperations.GetBindingExpression(tb, prop);
    if (binding != null) { binding.UpdateTarget(); }
}

这很好用。但是当我输入合法值时,控件周围的红线仍然存在并且永远不会再次删除。如何强制更新验证,以便删除红线?

【问题讨论】:

    标签: c# wpf validation


    【解决方案1】:

    您只需要通过整理SetErrorTemplate 方法来“清理”TextBox 的Validation.ErrorTemplate 属性的值:

    private void TextBox_ValidationErrorEventHandler(object sender, RoutedEventArgs e)
    {
        TextBox tb = sender as TextBox;
        if (tb != null)
        {
            DependencyProperty prop = TextBox.TextProperty;
            BindingExpression binding = BindingOperations.GetBindingExpression(tb, prop);
            if (binding != null)
            {
                binding.UpdateTarget();
                Validation.SetErrorTemplate(tb, null);
            }
        }
    }
    

    希望对你有帮助。

    【讨论】:

    • 完美!像魅力一样工作。 :-)
    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多