将ValidationRule和Value Converters组合在一个文本框中

时间:2011-02-20 22:35:28

标签: wpf validation binding valueconverter

我有一个简单的问题,我无法找到一个好的解决方案。 我有一个绑定到double属性值的文本框。用户可以在文本框中输入值,但我只想允许介于0和100之间的值。如果在文本框仍具有焦点时输入了无效值,则我希望在文本框周围显示一个红色框(UpdateSourceTrigger =“PropertyChanged” )。如果用户单击文本框,我想在UpdateSourceTrigger =“LostFocus”上使用值转换器来限制值。

很容易做验证规则或转换器,但我无法将它们组合在一起,因为我希望验证在UpdateSourceTrigger =“PropertyChanged”上触发,转换器应该在UpdateSourceTrigger =“LostFocus”上触发。不幸的是,我只能在TextBox.Text上设置绑定时选择其中一个。

关于如何实现此功能的任何好主意?

谢谢

/彼得

1 个答案:

答案 0 :(得分:0)

这是一个有趣的问题。我不确定我是否有完整的解决方案,但我想抛弃一些想法。

您如何创建一个派生自TextBox的新类?它可以有两个依赖属性,MinValue和MaxValue。然后它可以覆盖OnLostFocus。 (免责声明:我没有测试过以下代码。)

public class NumericTextBox : TextBox
{
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(double), typeof(NumericTextBox), new UIPropertyMetadata(Double.MinValue));

    public static readonly DependencyProperty MaxValueProperty =
        DependencyProperty.Register("MaxValue", typeof(double), typeof(NumericTextBox), new UIPropertyMetadata(Double.MaxValue));

    public double MinValue
    {
        get { return (double)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    public double MaxValue
    {
        get { return (double)GetValue(MaxValueProperty); }
        set { SetValue(MaxValueProperty, value); }
    }

    protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
    {
        base.OnLostFocus(e);

        double value = 0;

        // Parse text.
        if (Double.TryParse(this.Text, out value))
        {
            // Make sure the value is within the acceptable range.
            value = Math.Max(value, this.MinValue);
            value = Math.Min(value, this.MaxValue);
        }

        // Set the text.
        this.Text = value.ToString();
    }
}

这将消除对转换器的需求,您的绑定可以使用UpdateSourceTrigger = PropertyChanged来支持您的验证规则。

我的建议无可否认有其缺点。

  1. 这种方法要求您在两个地方拥有与验证相关的代码,并且需要匹配。 (也许你也可以覆盖OnTextChanged,并在那里设置红色边框。)
  2. 此方法要求您将规则放在视图层而不是业务对象中,您可能会或可能不会接受这些规则。
相关问题