2009-07-11 87 views
0

我有一個.xaml文件和一個與Binding共享值的.cs文件。更新值的WPF綁定問題

爲了簡單起見,我有1個按鈕和1個文本框。當文本框的文本沒有字符時,我想要禁用按鈕。

這裏是XAML的兩個代碼綁定:

<TextBox Name="txtSend" Text="{Binding Path=CurrentText,UpdateSourceTrigger=PropertyChanged}"></TextBox> 
    <Button IsEnabled="{Binding Path=IsTextValid}" Name="btnSend">Send</Button> 

中的.cs兩個屬性文件看起來像:

public string CurrentText 
    { 
     get 
     { 
      return this.currentText; 
     } 
     set 
     { 
      this.currentText = value; 
      this.PropertyChange("CurrentText"); 
      this.PropertyChange("IsTextValid"); 
     } 
    } 

    public bool IsTextValid 
    { 
     get 
     { 
      return this.CurrentText.Length > 0; 
     } 
    } 

this.PropertyChanged很簡單,就是調用PropertyChanged的方法來自INotifyPropertyChanged。

問題是,我必須調用CurrentText的Setter中的this.PropertyChange("IsTextValid");才能夠更改按鈕狀態。

問題1)這樣做的好方法...如果規則變得更復雜,我可能需要調用很多PropertyChanged ...?

問題2)我的按鈕在窗體加載時啓用。我怎樣才能使它從一開始就檢查方法?

回答

2

問題1:這是正確的。這樣做沒有問題。但是,您可以查看使用IDataErrorInfo的驗證。 (谷歌搜索它,你會發現很多很好的例子)

問題2:確保你的「currentText」字符串是用string.empty初始化的。因爲如果你沒有初始化它,它將爲空,並且IsTextValid的getter將引發異常,並且WPF將無法檢索該值。

或者那樣做:

public bool IsTextValid 
{ 
    get 
    { 
     return ! string.IsNullOrEmpty(this.CurrentText); 
    } 
} 
+0

+1和答案接受:) +25代表你的朋友。謝謝。 – 2009-07-11 17:34:46

0

你做這件事的方式是正確的。如果你有點懶(就像我),你應該看看NuGet包Fody.PropertyChanged。

您的代碼將簡化爲

public string CurrentText { get; set; } 

public bool IsTextValid { get { return this.CurrentText.Length > 0; } } 

Fody.PropertyChanged沒有休息爲您服務。它會自動添加所需的指令以通知CurrentText已更改,並且它甚至會檢測到IsTextValid取決於CurrentText並通知它。