WPF data binding with textbox binding example

0 votes
asked Jun 30, 2014 in WPF by Nikhil

I am very new to WPF and I am not able to understand why people writing binding expression sometime with Path property and sometime not. Same like that, the Source property also. Could someone help me understand with simple example please?

Share

1 Answer

+1 vote
answered Jun 30, 2014 by Nixon
selected Jun 30, 2014 by administrator
 
Best answer

Data binding is a concept helps to display data to the user through user interface. WPF has very strong support for data binding. WPF data binding can work with different kinds of data sources like POCO objects, ADO.NET objects (like Data table, dataset), XML objects, Dependency Objects.

We will take a simple example that will help you to understand the concept of data binding. I have 2 text boxes to display FirstName and LastName respectively. FirstName textbox is not using any data binding concept where as the LastName used databinding to display the data from a custom C# class called CustomerViewModel.

<Window x:Class="DataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:DataBinding"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">

    <Window.Resources>
        <vm:CustomerViewModel x:Key="myViewModel" LastName="Nixon" />
    </Window.Resources>

    <Grid x:Name="myGrid">
        <Label Content="First Name" HorizontalAlignment="Left" Margin="87,10,0,0" VerticalAlignment="Top"/>
        <TextBox Text="Jerry" HorizontalAlignment="Left" Height="23" Margin="195,14,0,0" 
                 TextWrapping="Wrap" VerticalAlignment="Top" Width="239"/>
        <Label Content="Last Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="88,55,0,0"/>
        <TextBox Text="{Binding LastName, Mode=TwoWay, Source={StaticResource ResourceKey=myViewModel}}" HorizontalAlignment="Left" Height="23" Margin="195,58,0,0" 
            TextWrapping="Wrap" VerticalAlignment="Top" Width="239"/>
    </Grid>
</Window>

namespace DataBinding
{
    public class CustomerViewModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }
    }
}

Output:
textbox databinding output

Explanation about data binding:

When the XAML compiler compiles the first textbox code, it will identify that the First Text Box’s Text property is going to display data from literal string. So, it does not need to do anything much to display that data.

But when it looks at the second text box, Text property content starts with open curly brace. When the compiler sees the “{“, it will identify that, the property is using some kind of Binding Expression to display data. This second text box is using a special class called “Binding” which is inherited from “MarkupExtension”. Binding class contains properties to hold information about binding.

In the below code, we have 4 major parts used for Data Binding. Even though the binding has more properties, following 4 parts are used very often.

textbox databinding syntax

First one is the “Target”. In this example, Target is “Text” property. This target property must be a Dependency Property. This is the property to which the data doing to be bind.

Next one is the “Source”. Source (Binding Source) is the instance of the object in which “LastName” property exist. i.e Instance of the object that holds the data. In our example, source is “CustomerViewModel”. Source can be specified in different ways.

In our example, we have created a instance of the “CustomerViewModel” and added into “Resources”. Resources are nothing but a dictionary which can hold Key Value pair. Then the resource dictionary is referenced as Static Resource. So at runtime, instance of the CustomerViewModel will be created and added into Resources with the Key “myViewModel”. Then the myViewModel will be used in the binding to read data from LastName property.
This will NOT be a usual way of specifying source.

Better way to do this is using “DataContext” which is available in the parent containers like Window, Page, Grid, Stack Panel etc. DataContext is also called as “Inherited Property”. Because, if you set data context on the parent container, that will be available for all of its children. So, at run time, if the current element is not having “Source” property with the Binding Expression, then it will automatically look for DataContext on its parent and use it as source.
Below code will give the same result as first example.

<Window x:Class="DataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:DataBinding"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">

    <Grid x:Name="myGrid">
        <Grid.DataContext>
            <vm:CustomerViewModel LastName="Nixon"/>
        </Grid.DataContext>

        <Label Content="First Name" HorizontalAlignment="Left" Margin="87,10,0,0" VerticalAlignment="Top"/>
        <TextBox Text="Jerry" HorizontalAlignment="Left" Height="23" Margin="195,14,0,0" 
                 TextWrapping="Wrap" VerticalAlignment="Top" Width="239"/>
        <Label Content="Last Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="88,55,0,0"/>
        <TextBox Text="{Binding LastName, Mode=TwoWay}" HorizontalAlignment="Left" Height="23" Margin="195,58,0,0" 
            TextWrapping="Wrap" VerticalAlignment="Top" Width="239"/>
    </Grid>
</Window>

Third one is the “Path” property. This property is used to specify the property from which the Target is going to get data. Path property can be explicitly specified as “Path=LastName” or implicitly as “LastName” after Binding keyword. When we use the “Path” explicitly, at runtime, first the “Binding” class instance will be created and then the Path property will be set with the value “LastName”. If the “Path” keyword is not mentioned explicitly, then at runtime, when the “Binding” class instance is created, “LastName” will be sent as a Constructor parameter to set value into “Path” property. End result is same for both.

Last one is “Mode”: Mode is used to specify the direction in which the data going to flow between the Binding Source and Binding Target.
There are four different ways of Binding Mode in WPF

“One Way” - Any changes in the Binding Source Property will be update to Target),

“Two Way” - Any changes in the Binding Source Property will be update to Target and any change in Target will be reflected in Binding Source.

“One Way To Source” - Any change in Target will be reflected in Binding Source automatically.

“One Time” - Source property value be initialized to the Target. After that, no changes in the Source will be reflected to Target.
Usually there will be a default mode of binding for different controls. The controls will be by default using those binding mode unless you change it. For example, TextBox will have default binding mode as “Two Way” where as TextBlock will be using default mode as “OneWay”.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...