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));
}
}
是啊,这实际上是这里的问题似乎。那么,它从来没有解释如何确切的属性工作在第一位。绑定到类的对象实例还是直接绑定到类上有区别? – Zephylir
“直接绑定到类”的绑定意味着绑定到类(即静态)属性?开始阅读这里:[数据绑定概述](https://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)。 – Clemens
顺便说一句,在MVVM体系结构模式中,所谓的“独立类”(名为'Code_Behind')通常称为*视图模型*。 – Clemens