这是一个有趣的问题。我不确定我有一个完整的解决方案,但我想提出几个想法。
您如何看待创建一个派生自 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 来支持您的验证规则。
诚然,我的建议有其缺点。
- 这种方法需要您在两个地方拥有与验证相关的代码,并且它们需要匹配。(也许您也可以覆盖 OnTextChanged,并在那里设置红色边框。)
- 这种方法要求您将规则放在视图层而不是业务对象中,您可能会也可能不会接受。