- You only need to implement this interface if you data class is going to change and you want those changes to propagate through to the UI.
- If you’re going to be reading data from the data base and simply displaying it on the screen then you can, and should, leave this interface off as it just adds unnecessary clutter
public class Customer : INotifyPropertyChanged
{
}
Define INotifyPropertyChanged Members,
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
In property setter invoke OnPropertyChanged by passing property name like,
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
In MainPage.xaml.cs add an ObservableCollection of customer object as Dependency
property inorder to make sure that UI is updating while we assigning that customer list
to another list or object.If we are making it as a normal property UI will update only if
we add new object to customerlist or any change occurs to the underlying properties.
public ObservableCollection<Customer> CustomerList
{
get { return (ObservableCollection<Customer>)
GetValue(CustomerListProperty); }
set { SetValue(CustomerListProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty CustomerListProperty =
DependencyProperty.Register("CustomerList",
typeof(ObservableCollection<Customer>), typeof(MainPage),
new PropertyMetadata(new ObservableCollection<Customer>()));
I also added a DependencyProperty FirstName in MainPage.xaml.cs just to show the binding of a simple DependencyProperty.
public string FirstName
{
get { return (string)GetValue(FirstNameProperty); }
set { SetValue(FirstNameProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register("FirstName", typeof(string), typeof(MainPage),
new PropertyMetadata(string.Empty));
In MainPage.XAML add a datagrid and textbox and bind it to the ObservableCollection and DependencyProperty respectively.
<data:DataGrid AutoGenerateColumns="True"
Width="400"
Height="300"
ItemsSource="{Binding ElementName=TestUC,
Path=CustomerList}"/>
<TextBox x:Name="NameTextBox"
Text="{Binding ElementName=TestUC, Path=FirstName, Mode=TwoWay}"
Width="100"
Height="25"
Margin="0,10,0,10" />