I'm a little bit lost, I am trying to bind a label on my GUI to a string in my code but it only seems to work if I place the code in my MainWindow() block and I can't update it from anywhere else.
This is my INotifyPropertyChanged class:
public class MyClass : INotifyPropertyChanged
{
private string _testLabel;
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
public string testLabel
{
get { return _testLabel; }
set
{
if (value != _testLabel)
{
_testLabel = value;
OnPropertyChanged("testLabelChanged");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
This is the MainWindow() block:
public MainWindow()
{
InitializeComponent();
testLabelName.DataContext = t;
t.testLabel = "Hello World 32432";
}
I've also declared this outside:
MyClass t = new MyClass();
This is a snippet from my XAML:
<Label Name="testLabelName" Content="{Binding Path=testLabel, Mode=OneWay}" Height="28" Margin="0,0,12,29" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="128" />
I tried testing it by using a button event to set the label, it seems to set but there are no changes on the GUI. I'm thinking that the GUI isn't updating on the PropertyChanged event. Is this right?
Thanks,
I think there is a small problem with your code. When you fire PropertyChanged event, you need to specify the name of the property. You code for the property should look like this:
public string testLabel
{
get { return _testLabel; }
set
{
if (value != _testLabel)
{
_testLabel = value;
OnPropertyChanged("testLabel"); // not testLabelChanged
}
}
}
Unless you specify the correct name for the property, UWP has no way to know which property has actually changed, and thus does not update the UI.