【发布时间】:2017-01-10 00:39:45
【问题描述】:
我有一个 UserControl 和一个名为 Value 的 int DependencyProperty。这绑定到UserControl 上的文本输入。
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(QuantityUpDown), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged, CoerceValue));
public int Value
{
get { return (int) GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static object CoerceValue(DependencyObject d, object basevalue)
{
//Verifies value is not outside Minimum or Maximum
QuantityUpDown upDown = d as QuantityUpDown;
if (upDown == null)
return basevalue;
if ((int)basevalue <= 0 && upDown.Instrument != null)
return upDown.Minimum;
//Stocks and ForEx can have values smaller than their lotsize (which is assigned to Minimum)
if (upDown.Instrument != null &&
upDown.Instrument.MasterInstrument.InstrumentType != Cbi.InstrumentType.Stock &&
upDown.Instrument.MasterInstrument.InstrumentType != Cbi.InstrumentType.Forex)
return Math.Max(Math.Min(upDown.Maximum, (int)basevalue), upDown.Minimum);
if (upDown.Instrument == null)
return Math.Max(Math.Min(upDown.Maximum, (int)basevalue), upDown.Minimum);
if (upDown.Instrument.MasterInstrument.InstrumentType == Cbi.InstrumentType.Stock ||
upDown.Instrument.MasterInstrument.InstrumentType == Cbi.InstrumentType.Forex)
return Math.Min(upDown.Maximum, (int)basevalue);
return basevalue;
}
如果用户在文本框中输入大于int.MaxValue 的值,当该值进入CoerceValue 时,baseValue 参数为1。如果我在@987654329 上提供验证值回调,也会发生同样的情况@。
我想自己处理这种情况,比如将传入的值设置为int.MaxValue。有没有办法做到这一点?
【问题讨论】:
-
如果您需要在绑定将值传递给源属性之前进行验证(即目标 == TextBox.Text,源 == QuantityUpDown.Value),您可以使用 Binding.ValidationRules 进行验证。
-
属性类型为
int。因此,传递给 Coerce 方法的值不能大于int.MaxValue。 -
@Clemens,很明显。然而,用户可以输入一个大于 int.MaxValue 的值。我该如何处理这种情况?