Published articles on other web sites*

Published articles on other web sites*

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 UpdateSourceTriggerproperty 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:
    <TextBox Height="23" HorizontalAlignment="Left"
            Margin="230,41,0,0" Name="textBox1" VerticalAlignment="Top"
            Width="120" Text="{Binding ElementName=textBox2,
            UpdateSourceTrigger=PropertyChanged}" />
    <TextBox Height="23" HorizontalAlignment="Left"
            Margin="230,98,0,0" Name="textBox2" VerticalAlignment="Top"
            Width="120" />
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!
WPF two way binding

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...