我的視圖模型實現了IDataErrorInfo
並且包含一個經過驗證的Message
屬性。如何驗證UserControl上的依賴項屬性?
我創建了一個UserControl
,其中Text
DependencyProperty
綁定到Message
。我的UserControl
上有幾個控件綁定到Text
(因此顯示Message
)。
如何直接在我的UserControl
中顯示未綁定到Message
的控件顯示驗證錯誤?
我的視圖模型實現了IDataErrorInfo
並且包含一個經過驗證的Message
屬性。如何驗證UserControl上的依賴項屬性?
我創建了一個UserControl
,其中Text
DependencyProperty
綁定到Message
。我的UserControl
上有幾個控件綁定到Text
(因此顯示Message
)。
如何直接在我的UserControl
中顯示未綁定到Message
的控件顯示驗證錯誤?
後相當長的一段時間,我設法弄清楚,我想我應該分享的情況下,其他人發現它有用的解決方案:
基本上我有我的Text
DependencyProperty
增加了PropertyChangedCallback
。在此回調中,我獲得Text
與視圖模型上的屬性之間的綁定,並檢查它是否存在驗證錯誤。如果找到ValidationError
,我會檢查UserControl
中綁定到Text
的所有控件,並使用Validation.MarkInvalid
爲它們綁定相同的錯誤。
編輯:
複製驗證錯誤一樣,如果我在一個按鈕單擊事件處理程序把下面的代碼能正常工作。但是,如果代碼位於PropertyChangedCallback
的Text
那麼沒有任何反應。有沒有人有辦法解決嗎?
// Get the binding from the Text property to the view model.
BindingExpression textBindingExpression = BindingOperations.GetBindingExpression(this,
MyUserControl.TextProperty);
// If there is a validation error, then give it to the control bindings.
if (textBindingExpression != null && textBindingExpression.ValidationError != null) {
Validation.MarkInvalid(this.MyTextBox.GetBindingExpression(TextBox.TextProperty),
textBindingExpression.ValidationError);
Validation.MarkInvalid(this.MyTextBlock.GetBindingExpression(TextBlock.TextProperty),
textBindingExpression.ValidationError);
}
你有沒有想過什麼?我有一個非常相似的問題,它讓我感到沮喪。 – Dude0001
這可以通過使UserControl實現IDataErrorInfo以及視圖模型來實現。有更好的解決方案嗎? – Coder1095