Wednesday, February 22, 2012

WPF - Two Way Textbox Binding in WPF

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 this article i will explained Two-Way binding between Textboxes in a WPF application, using the UpdateSourceTrigger property of the Binding class.


Step 1
Create a Wpf Application and give the solution name as SolTwoWayBindingWPF.


Step 2
Open MainWindow.Xaml and add two textboxes. Since we need to bind these textboxes with two-way DataBinding,it is look like this
<Grid>
        
        <TextBox x:Name="txtbox1"  Height="23" HorizontalAlignment="Left" 
         Margin="76,115,0,0"  VerticalAlignment="Top" Width="358" />
        
        <TextBox x:Name="txtbox2" Text="{Binding ElementName=txtbox1,Path=Text,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
         Height="23" HorizontalAlignment="Left" Margin="76,173,0,0"  
         VerticalAlignment="Top" Width="358" />
        
    </Grid>


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.

Step 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.


Output
Click on image for better view

Download

No comments:

Post a Comment