2017-07-11 28 views
1

在一個WinForms ReactiveUI視圖模型我有一個屬性setter的屬性,可以引發ArgumentException:ReactiveUI:異常後綁定失去了在屬性setter

public string Foo 
    { 
     get { return _foo; } 
     set 
     { 
      if (value == "ERR") throw new ArgumentException("simulate an error"); 
      this.RaiseAndSetIfChanged(ref _foo, value); 
      Debug.WriteLine(string.Format("Set Foo to {0}", _foo)); 
     } 
    } 
private string _foo; 

在查看屬性foo是綁定到一個文本框uiFoo:

this.Bind(ViewModel, vm => vm.Foo, v => v.uiFoo.Text); 

綁定工作正常(如setter的Debug.WriteLine的輸出所示)。 但是在輸入引發ArgumentException的「ERR」後,該綁定不再起作用。

在setter中的異常之後,我必須採取什麼解決方案來恢復(或保持)工作狀態的綁定?

+0

你可能會在它碰到框架的最上層之前嘗試捕捉並處理異常。一個二傳手如何能夠正常提出異常? –

+0

我建議不要在setter中拋出異常。如果值無效,則設置者應該返回,而不將該值設置爲支持字段 –

+0

從setter中拋出異常是不正確的模式。 https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/property –

回答

0

正如我們在您的問題的評論中提到的,屬性獲取者或設置者中的異常是BIG NO,NO

以下是兩種可用的解決方案:在嘗試讀取它時使用無效值或使用setter方法。我更喜歡後者;特別是當你拋出一個ArgumentException,這應該只在提供參數時使用。 (打破這個規則可能是代碼的消費者困惑:「爲什麼我會得到一個ArgumentException當我沒有要求任何功能?」)

這裏有一個辦法做到這一點:

public string Foo { get; private set; } 

public void SetFoo(string value) 
{ 
    if(value == "invalid value") 
     thrown new ArgumentException($"{nameof(Foo)} can't be set to '{value}'", nameof(value)); 

    Foo = value; 
}