2009-05-18 28 views
5

比方說,我有一個簡單的類數據綁定和setter方法拋出異常

public class Person 
{ 
    public string Name { get; set; } 

    private int _age; 
    public int Age 
    { 
    get { return _age; } 
    set 
    { 
     if(value < 0 || value > 150) 
     throw new ValidationException("Person age is incorrect"); 
     _age = value; 
    } 
    } 
} 

然後我想設置該等級的綁定:

txtAge.DataBindings.Add("Text", dataSource, "Name"); 

現在,如果我輸入不正確時代價值文本框(比如說200)在setter中的異常將被吞噬,我將無法做任何事情,直到我改正了文本框中的值。我的意思是文本框將無法放鬆焦點。這一切都是沉默的 - 沒有錯誤 - 你無法做任何事情(甚至關閉表格或整個應用程序),直到你改正了價值。

這看起來像一個錯誤,但問題是:這是什麼解決方法?

+1

是否有你拋出異常而不是實現IDataErrorInfo的原因?我認爲後者是WinForms中更習慣的方法(並且在WPF中它仍然很好地工作)。 – 2009-05-19 00:11:19

回答

3

好,這裏是解決方案:

我們需要處理BinsingSource,CurrencyManager的或BindingBanagerBase類的BindingComplete事件。代碼可能看起來像這樣:

/* Note the 4th parameter, if it is not set, the event will not be fired. 
It seems like an unexpected behavior, as this parameter is called 
formattingEnabled and based on its name it shouldn't affect BindingComplete 
event, but it does. */ 
txtAge.DataBindings.Add("Text", dataSource, "Name", true) 
.BindingManagerBase.BindingComplete += BindingManagerBase_BindingComplete; 

... 

void BindingManagerBase_BindingComplete(
    object sender, BindingCompleteEventArgs e) 
{ 
    if (e.Exception != null) 
    { 
    // this will show message to user, so it won't be silent anymore 
    MessageBox.Show(e.Exception.Message); 
    // this will return value in the bound control to a previous correct value 
    e.Binding.ReadValue(); 
    } 
} 
+0

huuh ...考慮實施IDataErrorInfo – 2009-05-29 00:27:18