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