2016-10-30 156 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