Binding Text of One controls with another in WPF

Introduction

Supposewe need to change the text of Label control whenever the text of TextBox control get changes or whyle typing in the TextBox in windows. For that task have to use TextChange event of TextBox in code behind . And have to write couple of code in that function.

For Example type casting of sender etc, assign the text of TextBox to Text of Label controls, the following code give an example of code bind action

Code:

TextBox TB=(Sender)TextBox;

label1.Text=TB.Text;

We could not change the text of Label Control with out using Code Behind, but WPF elemenets that problem, we can change Text of Label control without using Code Behind . Bellow code example explains how to change the text of controls when other controls text get changes.

The following code takes one TextBox and one TextBlock Control. The TextBox and TextBox's text property are binded with TextBlock controls. Here the binding property of TextBlock is used to bind Text of TextBox.

Code

<Window x:Class="Example00.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

<Grid >
<Grid.RowDefinitions >
<
RowDefinition Height="*" />
<
RowDefinition Height="*" />
</
Grid.RowDefinitions>
<TextBox Name="mySourceElement" Grid.Row="0" Height="20" Width="200">Hello World</TextBox>

<TextBlock Text="{Binding ElementName=mySourceElement,Path=Text }" Grid.Row="1" Width="200" />
</Grid>
</
Window>