【发布时间】:2012-07-25 11:47:47
【问题描述】:
编辑:这是对本文原始版本的简化更新。
在 WPF 中,我实现了一个 UserControl(称为“NumericTextBox”),它使用与 Text 属性保持同步的 *DependencyProperty 'Value' >文本框(xaml):
<TextBox.Text>
<Binding Path="Value"
Mode="TwoWay"
ValidatesOnDataErrors="True"
NotifyOnValidationError="True"
UpdateSourceTrigger="PropertyChanged" />
</TextBox.Text>
出于验证目的,我使用 IDataErrorInfo 接口 (xaml.cs):
public partial class NumericTextbox : Textbox, IDataErrorInfo {
public double Value {
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double),
typeof(NumericTextBox),
new PropertyMetadata(default(double)));
public string this[string columnName]
{
// Never gets called!
get { /* Some validation rules here */ }
}
}
如源代码中所述,get 属性实际上永远不会被调用,因此不会发生验证。您看到问题的原因了吗?
Edit2:根据伦理逻辑的回答,我重新构建了我的代码。 NumericTextBox 现在使用底层视图模型类,该类提供绑定到 TextBox 的 Text 属性的依赖属性 Value em> 由 NumericTextBox 声明。此外,NumericTextBox 使用视图模型作为其数据上下文。 viewmodel 现在负责检查 Value 属性的变化。由于 NumericTextBox 的值限制是可自定义的(例如可以调整最小值),它会将这些设置转发给 viewmodel 对象。
【问题讨论】:
-
你的问题到底是什么?
-
抱歉,刚刚更新了帖子。
-
所以你想检查用户是否只写数字?我能理解你的问题吗?
-
还有一些附加条件...
-
嗨,为什么您希望该属性仅是依赖属性。为什么不能将验证应用于绑定到 TextBox 的 Text 属性的 ViewModel 属性
标签: c# wpf validation xaml idataerrorinfo