May 26, 2023 08:15 by
Peter
Data binding is one of the best features the human race has ever devised. Binding a property of a UI Element to a property in the code behind can accomplish any task. It is magic, in a nutshell. Once the properties are bound, we must continue to notify the UI whenever the property's value is modified in the code. INotifyPropertyChanged is useful in this situation.
Because it is an interface, it must first be implemented. However, the procedure is not arduous. Here is the code for my primary page in my new Silverlight project:
publicpartialclassMainPage : UserControl
{
privatestring _names;
publicstring Names
{
get
{
return _names;
}
set
{
_names = value;
}
}
public MainPage()
{
InitializeComponent();
}
privatevoid MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
Names = "This is the Text";
}
}
The property "Name" I have here is bound with the textblock in XAML, here is the code:
<UserControlx:Class="PropertyChangedDescribed.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Loaded="MainPage_OnLoaded"
x:Name="TestingPropertyChanged"
d:DesignHeight="300"d:DesignWidth="400">
<Gridx:Name="LayoutRoot"Background="White">
<TextBlockText="{Binding Names, ElementName=TestingPropertyChanged}"/>
</Grid>
</UserControl>
As you can see, the textblock has it's "text" property bound with our code behind's property "Name". Right now, no matter what you set the value of "Name", it will never be reflected onto the UI. So, what we want is, every time we change the value of our property "Name," the text block has its value changed too. In order to do this, we need to implement the interface INotifyPropertyChanged. Here is the modified main page's code to do so:
publicpartialclassMainPage : UserControl, INotifyPropertyChanged
{
privatestring _names;
publicstring Names
{
get
{
return _names;
}
set
{
_names = value;
OnPropertyChanged("Names");
}
}
public MainPage()
{
InitializeComponent();
}
privatevoid MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
Names = "This is the Text";
}
publicevent PropertyChangedEventHandler PropertyChanged;
privatevoid OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
}
So this is how you can implement INotifyPropertyChanged in Silverlight.