Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, July 19, 2012

DataBinding in WPF

DataBinding in WPF

Introduction

WPF provides a simple and powerful way to auto-update data between the business model and the user interface. This mechanism is called DataBinding. Everytime when the data of your business model changes, it automatically reflects the updates to the user interface and vice versa. This is the preferred method in WPF to bring data to the user interface.
Databinding can be unidirectional (source -> target or target <- source), or bidirectional (source <-> target).
The source of a databinding can be a normal .NET property or a DependencyProperty. The target property of the binding must be a DependencyProperty.
To make the databinding properly work, both sides of a binding must provide a change notification that tells the binding when to update the target value. On normal .NET properties this is done by raising the PropertyChanged event of the INotifyPropertyChanged interface. On DependencyProperties it is done by the PropertyChanged callback of the property metadata
Databinding is typically done in XAML by using the {Binding} markup extension. The following example shows a simple binding between the text of a TextBox and a Label that reflects the typed value:
 
<StackPanel>
    <TextBox x:Name="txtInput" />
    <Label Content="{Binding Text, ElementName=txtInput, 
                     UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
 
 

DataContext

Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data object it visualizes. If you don't explicity define a source of a binding, it takes the data context by default.
The DataContext property inherits its value to child elements. So you can set the DataContext on a superior layout container and its value is inherited to all child elements. This is very useful if you want to build a form that is bound to multiple properties of the same data object.
 
<StackPanel DataContext="{StaticResource myCustomer}">
    <TextBox Text="{Binding FirstName}"/>
    <TextBox Text="{Binding LastName}"/>
    <TextBox Text="{Binding Street}"/>
    <TextBox Text="{Binding City}"/>
</StackPanel>
 
 

ValueConverters

If you want to bind two properties of different types together, you need to use a ValueConverter. A ValueConverter converts the value from a source type to a target type and back. WPF already includes some value converters but in most cases you will need to write your own by implementing the IValueConverter interface.
A typical example is to bind a boolean member to the Visibility property. Since the visibility is an enum value that can be Visible, Collapsed or Hidden, you need a value converter.
 
<StackPanel>
    <StackPanel.Resources>
        <BooleanToVisibilityConverter x:Key="boolToVis" />
    </StackPanel.Resources>
 
    <CheckBox x:Name="chkShowDetails" Content="Show Details" />
    <StackPanel x:Name="detailsPanel" 
                Visibility="{Binding IsChecked, ElementName=chkShowDetails, 
                             Converter={StaticResource boolToVis}}">
    </StackPanel>
</StackPanel>
 
 
The following example shows a simple converter that converts a boolen to a visibility property. Note that such a converter is already part of the .NET framework.
 
public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          CultureInfo culture)
    {
        if (value is Boolean)
        {
            return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
        }
 
        return value;
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, 
                              CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
 
 
Tip: you can derive your value converter from MarkupExtension and return its own instance in the ProvideValue override. So you can use it directly without referencing it from the resources.
Another Tip: When you get the error "No constructor for type '...' has 0 parameters.", you need to add an default constructor to your converter, even it's not needed. Just for the WPF designer.

No comments:

Post a Comment