It requires knowledge of Binding concept in WPF.
Following are the different ways of Binding in WPF:
- Datacontext binding:
Binds property to Datacontext object.
E.g.: Consider following Xaml snppet.
- <TextBox Text="{Binding}" />
Binds Text to Datacontext object.
- Property Binding with change notification from source:
Consider following Xaml snppet.
- <TextBox Text="{Binding Path=EmpName}" />
Corresponding View Model looks as follows:
- public class ViewModel: System.ComponentModel.INotifyPropertyChanged
- {
- private string _EmpName = "Hi to Binding";
- private string EmpName
- {
- get
- {
- return _EmpName;
- }
- set
- {
- _EmpName = value;
- OnPropertyChanged("EmpName");
- }
- }
- public event System.ComponentModel.PropertyChangedEventHandler OnPropertyChangedEvent;
- protected virtual void OnPropertyChanged(string propertyName)
- {
- if (this.OnPropertyChangedEvent != null)
- {
- this.OnPropertyChangedEvent(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
- }
- }
- }
- Property Binding with change notification from client:
- <TextBox Text="{Binding Path=EmpName,
- UpdateSourceTrigger=PropertyChanged}" />
UpdateSourceTrigger notifies when notification should be sent to source about change. Default UpdateSourceTrigger is LostFocus.
If UpdateSourceTrigger is set to LostFocus then it mean when Text value of textbox changes, it notifies to source on Lostfocus e.g. if User types in textbox then it will not change EmpName. It changes its value after losing focus.
Using UpdateSourceTrigger=PropertyChnaged, changes EmpName as soon as you type value in textbox.
- FallBack value:
- <TextBox Text="{Binding Path=EmpName,
- FallbackValue='Employee Name'}" />
FallbackValue is displayed if element is unable to resolve the binding i.e. if the property does not exists in the ViewModel.
- Element Binding:
You can bind UI element to other UI element.
- <TextBox Name="txt1" Text="{Binding Path=EmpName}" />
- <TextBox Name="txt2" Text="{Binding Path= Text,
- ElementName=txt1}" />
- Binding with Converter:
Converter class as follows:
- public class BooleanToTextConverter: System.Windows.Data.IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
-
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
-
- }
- }
Add Namespace of BooleanToTextConverter class in windows tag as:
- <Window …..
- Xmlns:common="clr-namespace:Common.Library;assembly:common.Library">
Create instance of converter class in XAML:
- <Window.Resources>
- <common:BooleanToTextConverter x:key="TextConverter"/>
- </Window.Resources>
Bind this instance as:
- <TextBox Name="txt1" Text="{Binding Path=EmpName,
- Converter={StaticResource TextConverter }}" />