編輯:這是此帖子原始版本的簡化更新。基於IDataErrorInfo的驗證不起作用
在WPF我實現了一個用戶控件(稱爲 'NumericTextBox'),其使用的a *的DependencyProperty '值' 被保持同步與文本框(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
屬性實際上是永遠不會被稱爲,因此沒有驗證發生。你看到問題的原因嗎?
編輯2:基於ethicallogics的答案我重構了我的代碼。該NumericTextBox現在使用的底層視圖模型類,它提供一個依賴屬性值綁定到文本框這是由NumericTextBox宣佈的文本屬性。另外NumericTextBox使用viewmodel作爲其datacontext。 Viewmodel現在負責檢查Value屬性的更改。由於NumericTextBox的值限制是可定製的(例如,最小值可以調整),因此將這些設置轉發給視圖模型對象。
什麼是您的問題? – harry180 2012-07-25 12:04:20
對不起,剛更新了帖子。 – Bastian 2012-07-25 12:08:38
所以你想檢查用戶是否只寫數字?我很好理解你的問題? – harry180 2012-07-25 12:14:35