2009-10-21 71 views
2

如何在用戶點擊按鈕時強制驗證?在C#中執行WPF元素驗證?

有人會認爲這應該很容易,因爲如果元素值是有效的,你總是必須做點什麼。

private void buttonOk_Click(object sender, RoutedEventArgs e) 
{ 
    // How can I force the validation here? So that empty values are not allowed (validator doesn't allow those) 

    if (Validation.GetHasError(textBoxURI) || 
     Validation.GetHasError(textBoxName)) // These return valid values if user has not changed values in fields. 
     return; 

    DialogResult = true; 
    this.Close(); 
} 

正如您可以猜到,空值,根據我的驗證是無效的(如果我輸入的東西到文本框),然後清空它和模糊,它會顯示無效值的焦點。

附註:UpdateSourceTrigger不會影響初始值未驗證的相關問題。

回答

1

你需要調用UpdateSource上的BindingExpression。這一個文本框,在這裏我們強制驗證發生的例子:

BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty); 
exp.UpdateSource(); 
0

你有沒有嘗試使用MultiTriggerMultiDataTrigger

使用此功能,您可以定義您現在的規則......以及您可能想到的任何其他驗證規則。

Check this out:

+0

我沒有讀到它,是的,有人提出了一些條件,制止「確定」按鈕,使用這些被啓用... – Ciantic 2009-10-21 17:49:22

+0

如果你知道如何使用MultiTrigger將DialogResult設置爲true確實告訴我,我很難做到這一點。 – Ciantic 2009-10-21 19:55:36