Zephylir Zephylir - 1 month ago 5
C# Question

WPF Databinding, value won't update

I know this is terribly common issue, but I just can't get the button to update to "Pressed1" and "Pressed2" content when changing "Default" of buttonContent. Having looked at few questions, I can't find the answer that'd work for me, I simply can't find out what is wrong here, so here's the crappy code:

The window with a button

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();
}
}


And here's the separate class

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));
}
}

Answer

You are not setting the property, but the backing field. Hence the PropertyChanged event is not fired.

Replace

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

with

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

Besides that, it is a widely accepted convention to write property names with Pascal casing, i.e. ButtonContent instead of buttonContent.

Moreover, your property setter looks odd (probably because you try to squeeze too much code in one line).

Instead of

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

it should certainly be

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