Reputation: 61
i am trying to understand the concept of data binding, i learnt that data binding is the way that you can bind UI elements to objects so that any change in either of them will effect the other(in case of two way binding), but this is not working in this simple example :
my class :
namespace dataBinding.Models
{
public class person
{
public string name { get; set; }
public override string ToString()
{
return this.name;
}
}
}
the XAML :
xmlns:models="using:dataBinding.Models"
<Page.DataContext>
<models:person x:Name="personObject" name="Person's Name"/>
</Page.DataContext>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Right"
Text="{Binding name, Mode=TwoWay}" />
<Button Name="changeNameButton"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Content="Change Name" />
the C# Code :
namespace dataBinding
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
changeNameButton.Click += ChangeNameButton_Click;
}
private void ChangeNameButton_Click(object sender, RoutedEventArgs e)
{
personObject.name = "New Name";
}
}
}
when i run the app the TextBlock shows "Person's Name" but clicking the changeName Button doesn't change what is shown in the TextBlock so, what am i missing here ?
Upvotes: 0
Views: 157
Reputation: 19790
Your missing the INotifyPropertyChanged
interface implementation. Your XAML does not know it has been changed.
Easy to fix, use https://github.com/Fody/PropertyChanged
It will add the code to notify everyone that the property has changed.
[ImplementPropertyChanged]
public class person
{
public string name { get; set; }
public override string ToString()
{
return this.name;
}
}
Upvotes: 2