【问题标题】:How to Handle validation within a custom TextBox如何处理自定义文本框内的验证
【发布时间】:2021-01-15 15:58:25
【问题描述】:

我有一个自定义的 TextBox 来处理测量值(英尺、英寸、毫米),它有几个依赖属性来确定当框失去焦点时框的格式应该是什么。我在OnLostFocus 函数中进行了所有转换,因为转换中间输入不起作用。在OnLostFocus 中,我根据其他一些 DP 属性将值转换为数字并设置测量属性。这一切都很好。

我的问题是,我如何处理验证?当有人输入无效值时,我希望文本框变为红色,就像您可以使用具有 ValidatesOnExceptions=true 的绑定一样。我在 OnLostfocus 的 catch 块中尝试了类似下面的内容

    protected override void OnLostFocus(RoutedEventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                Text = "0";
            }
            if (IsMetric)
            {
                var measurement = convertStuffHere();
                Text = measurement.Text;
                Measurement = measurement.Value;
            }
            else
            {
                var measurement = convertOtherStuffHere();
                // convert and formatting stuff here...

                Text = measurement.Text;
                Measurement = measurement.Value;
            }

            var binding = this.GetBindingExpression(TextBox.TextProperty);
            if (binding != null)
                Validation.ClearInvalid(this.GetBindingExpression(TextBox.TextProperty));

        }
        catch (Exception)
        {
            var rule = new DataErrorValidationRule();
            var binding = this.GetBindingExpression(TextBox.TextProperty);
            if (binding != null)
            {

                ValidationError validationError = new ValidationError(rule, this.GetBindingExpression(TextBox.TextProperty));

                validationError.ErrorContent = "This is not a valid input";

                Validation.MarkInvalid(this.GetBindingExpression(TextBox.TextProperty), validationError);
            }


        }
        finally
        {
            base.OnLostFocus(e);
        }
    }

这几乎可以正常工作,但验证错误出现较晚。在文本框周围显示一个红色框之前,我必须失去焦点、获得焦点并再次失去焦点。

我像<myns:MeasurementTextBox Text="{Binding MeasurementText1, ValidatesOnExceptions=True}" Margin="10" IsMetric="True"></myns:MeasurementTextBox>一样使用它

【问题讨论】:

    标签: wpf wpf-controls


    【解决方案1】:

    您可以使用 TextBoxBase.TextChanged 事件代替 UIElement.LostFocus。

    【讨论】:

    • 啊哈。这行得通。我最终解析了 TextChanged 中的值,然后在失去焦点的情况下进行格式化。我担心在 TextChanged 中执行此操作会在每次输入输入时强制更新绑定(我希望它在 LostFocus 上),但我猜 UpdateSourceTrigger 是用来控制它的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多