Data Binding on Form Windows
Windows and controls have a DataContext that can be assigned a data source and accessed by all their children.
Individual controls can be bound by adding the following to the attribute that is bound:
Text="{Binding path=Key}"
where Key is the name of the property on the bound object, and text is the controls attribute the value is being bound to. If no other parameters are used in the binding the path= can be dropped.
If the DataContext is set to a list, it has the notion of a current instance. Controls can be bound to properties of the current instance, and will display values that stay in sync as the current selection changes. To make a multiple item control stay in sync, and allow it to change the current object the list should be bound with the property set that controls that feature, for a list box the property is
IsSyncronisedWithCurrentObject. The whole list is bound with
Text="{Binding}"
Data Binding with Background Updates that need to Appear in the UI
Again, when using the MVVM pattern, there are two options for creating bindable data, that will allow another thread in the background to update the underlying data, and have that change reflected in the view.
Note that for Lists of data the ObservableCollection<> class provides all the functionality required to handle collection operations.
Dependency Properties
The properties in the VM class are implemented as Dependency Properties. (macro propdp.) This requires the VM to derive from DependencyObject.
For Example:
public int Key
{
get { return (int)GetValue(KeyProperty); }
set { SetValue(KeyProperty, value); }
}
public static readonly DependencyProperty KeyProperty =
DependencyProperty.Register("Key",
typeof(int),
typeof(CharacterMainViewModel),
new UIPropertyMetadata(0));
On the plus side you are done, and the property will support Animation.
INotifyPropertyChanged
In this case the VM must implement the INotifyPropertyChanged interface.
This involves exposing a PropertyChanged event only.
The typical implementation would involve a method like this:
public void OnPropertyChanged(string prop)
{
if (null != PropertyChanged)
PropertyChanged(this,
new PropertyChangedEventArgs(prop));
}
and every property using this method to raise an event when the value changes:
public int Key
{
get { return this.UnderlyingCharacter.Key; }
set {
this.UnderlyingCharacter.Key = value;
OnPropertyChanged("Key");
}
}
Where UnderlyingCharacter is the Model object instance in this example. Making sure that the properties are used to update the data in every case is required to keep the UI in sync.