WPF Data Binding in VS 2010


Till VS2008 programmers have to write binding statements mostly directly in XAML – otherwise we have to use Expression Blend. Cider/WPF designer in Visual Studio 2008 was not powerful enough for handling Data binding. Visual Studio 2010 (Beta 1) has powerful Data Binding tooling mechanism in-built much like Expression blend.

Let’s walk step by step of how to use Data Binding tools in VS 2010. We have a simple WPF window like this –

<StackPanel>

        <Label>Enter your name:</Label>
        <TextBox x:Name="textUser"></TextBox>
       
<Label>Name entered by you is:</Label>
       
<TextBox x:Name="txtMessage"></TextBox>

</StackPanel>

 

To databind the lblMessage label with text textbox select the label in window and press F4 or select properties. In the properties windows select Content property and select the “Advanced Properties” icon (newly added in VS 2010). In the context menu select “Apply Data Binding” option

 

In the New Data Binding window select ElementName tab (as we have not set any DataContext). We want to bind it with another element which in this case is the text box. RelativeSource and StaticResource tabs are used for Relative Source and Static Resources.

 

Select Path tab and select Text property, as we want to bind to the Text property of txtUser source text box control.

 

If we want to use Converter, we can use Converter tab – in this case we are not going to use one. Options tab allows to set Data Binding options like Mode and UpdateSourceTrigeer. In this example we are setting Data Binding Mode as Two Way (so that updating Target TextBox also updates Source). We are also setting UpdateSourceTrigget property as PropertyChanged so that changes happen at key change event for text box.

 

Once done watch the Text property of the txtMessage text box –

VS 2010 IDE has set it as –

<TextBox x:Name="txtMessage" Text="{Binding ElementName=txtMessage, Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>

This is the same we would’ve done in VS 2008 / XAML manually.

One more interesting info here – similar to many property window/grid Data binding window also uses Reflection heavily – once we specified Source Element, it used Reflection to get a list of all the properties of the control to bind.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s