2016-10-30 218 views
0

我知道這是非常普遍的問題,但是我更改buttonContent的默認值時,無法將按鈕更新爲「Pressed1」和「Pressed2」內容。說完看着幾個問題,我無法找到願意爲我工作的回答,我根本無法找出什麼是錯在這裏,所以這裏的糟糕代碼:WPF數據綁定,值不會更新

與按鈕的窗口

public partial class MainWindow : Window 
{ 
    Code_Behind cB; 
    public MainWindow() 
    { 
     cB = new Code_Behind(); 
     this.DataContext = cB; 
     InitializeComponent(); 
    } 
    private void button_Click(object sender, RoutedEventArgs e) 
    { 
     cB.buttonPressed(); 
    } 
} 

而這裏的單獨的類

public class Code_Behind : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    private string _buttonContent = "Default"; 
    public string buttonContent 
    { 
     get { return _buttonContent; } 
     set { 
       if (_buttonContent != value) 
        { 
         buttonContent = value; 
         OnPropertyChanged("buttonContent"); 
        } 
      } 
    } 
    public void buttonPressed() 
    { 
     int timesPressed = 0; 
     if (timesPressed != 1) 
     { 
       _buttonContent = "Pressed1"; 
       timesPressed++; 
     } 
     else if (timesPressed != 2) 
     { 
       _buttonContent = "Pressed2"; 
       timesPressed++; 
       timesPressed = 0; 
     } 
    } 
    protected void OnPropertyChanged(string name) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); 
    } 
} 

回答

0

您沒有設置該屬性,但支持字段。因此,PropertyChanged事件未被觸發。

更換

_buttonContent = "Pressed1"; 
... 
_buttonContent = "Pressed2"; 

buttonContent = "Pressed1"; 
... 
buttonContent = "Pressed2"; 

此外,它是用Pascal大小寫寫屬性名稱被廣泛接受的慣例,即ButtonContent而不是buttonContent。此外,你的屬性設置器看起來很奇怪(可能是因爲你試圖在一行中擠壓太多的代碼)。

而不是

set 
{ 
    if (_buttonContent != value) 
    { 
     _buttonContent = value; 
    } 
    OnPropertyChanged("buttonContent"); 
} 

它當然應該

set 
{ 
    if (_buttonContent != value) 
    { 
     _buttonContent = value; 
     OnPropertyChanged("buttonContent"); 
    } 
} 
+0

是啊,這實際上是這裏的問題似乎。那麼,它從來沒有解釋如何確切的屬性工作在第一位。綁定到類的對象實例還是直接綁定到類上有區別? – Zephylir

+1

「直接綁定到類」的綁定意味着綁定到類(即靜態)屬性?開始閱讀這裏:[數據綁定概述](https://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)。 – Clemens

+0

順便說一句,在MVVM體系結構模式中,所謂的「獨立類」​​(名爲'Code_Behind')通常稱爲*視圖模型*。 – Clemens