WPF: Two way TextBox Binding

In WPF, one of the important features provided is to bind one XAML element to another element, without using any code. This reduces code-behind requirements for the XAML file. In the code segment below, I have explained Two-Way binding between Textboxes in a WPF application, using the UpdateSourceTrigger property of the Binding class.

Task 1: Open VS2010 and create a WPF application.

Task 2: Open MainWindow.Xaml and add two textboxes. Since we need to bind these textboxes with two-way DataBinding, we need to set the following properties of the Binding class:

Mode: Used to define the Strategy for the data binding with following values:

  • OneWay
  • TwoWay
  • OneWayToSource etc.

ElementName: The source WPF element name

Path: The Dependency Property of the Source WPF Element

UpdataSourceTrigger: The Event to be raised on the source element dependency property

Write the following XAML as shown below:

<Grid>
<
TextBox Height="23" HorizontalAlignment="Left"
Margin="230,41,0,0" Name="textBox1" VerticalAlignment="Top"
Width="120" Text="{Binding ElementName=textBox2,
Path=Text,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
<
TextBox Height="23" HorizontalAlignment="Left"
Margin="230,98,0,0" Name="textBox2" VerticalAlignment="Top"
Width="120" />
</
Grid>

Task 3: Run the application, type some text in the first textbox and you will observe that the same text automatically replicates in the second textbox. Similarly, type some text in second textbox and the same text gets added in the first textbox. This is all happening using plain XAML and not a single line of C# code!

OUTPUT

WPF two way binding






About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

1 comment:

Anonymous said...

Hi,

i have a question. I have 2 TextBox. I type numbers in the first one and the summ of the numbers should be placed on the second one. Canthis be done?

thx