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.
Binds Text to Datacontext object.- <TextBox Text="{Binding}" />
- Property Binding with change notification from source:
Consider following Xaml snppet.
Corresponding View Model looks as follows:- <TextBox Text="{Binding Path=EmpName}" />
- 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:
UpdateSourceTrigger notifies when notification should be sent to source about change. Default UpdateSourceTrigger is LostFocus.- <TextBox Text="{Binding Path=EmpName,
- UpdateSourceTrigger=PropertyChanged}" />
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:
FallbackValue is displayed if element is unable to resolve the binding i.e. if the property does not exists in the ViewModel.- <TextBox Text="{Binding Path=EmpName,
- FallbackValue='Employee Name'}" />
- 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:
Add Namespace of BooleanToTextConverter class in windows tag as:- public class BooleanToTextConverter: System.Windows.Data.IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- //do something and return value to UI element
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- //do something and return value to ViewModel
- }
- }
Create instance of converter class in XAML:- <Window …..
- Xmlns:common="clr-namespace:Common.Library;assembly:common.Library">
Bind this instance as:- <Window.Resources>
- <common:BooleanToTextConverter x:key="TextConverter"/>
- </Window.Resources>
- <TextBox Name="txt1" Text="{Binding Path=EmpName,
- Converter={StaticResource TextConverter }}" />

Santhakumar MunuswamyPosted Dec 26, 2015, 2:07 AM
Thanks for sharing