Updated on Kisan Patel
Data binding is the process that establishes a connection between the application User Interface(UI) and data sources. This means that if you modify data in a control, that change is also reflected in the original data source. In other words, data binding is a two-way process in which the changes made in the data source are reflected in the control and vice versa.
You can implement data binding in a WPF application by using the code-behind file of an application or in XAML file. WPF also needs to have a target and a source for data binding. You can select the public property of a control in WPF to bind your data, for example, the Text property of the TextBox control.
Binding is specified in XAML using the Binding
markup extension, placed on the target property. The Binding properties we need to set are the source object and the source property, if any binding is to actually take place.
For Example:
<TextBlock Text="This is a sizing text" FontSize="{Binding Path=Value, ElementName=_slider}" TextAlignment="Center" VerticalAlignment="Center"/> <Slider x:Name="_slider" Minimum="10" Maximum="80" Value="30"/>
The equivalent code, if binding from code-behind file:
var binding = new Binding("Value"); binding.ElementName = "_slider"; _text.SetBinding(TextBlock.FontSixeProperty, binding);
WPF data binding supports different types of binding modes between the target and the source. The data flow in a binding can be either from the target to the source or from the source to the target.
You should specify the mode of data binding while binding the data in a WPF application. The Mode
property defines the binding mode to determine the direction of the data flow.
Four types of binding modes in WPF:
Lets create new WPF application and name it as “WPFBindingDemo” then add below line of code to MainWindow.xaml file:
MainWindow.xaml
<Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Text="This is a sizing text" FontSize="{Binding Path=Value, ElementName=_slider}" TextAlignment="Center" VerticalAlignment="Center"/> <Slider x:Name="_slider" Grid.Row="1" Minimum="10" Maximum="80" Value="30"/> <TextBox Text="{Binding Value, ElementName=_slider}" Grid.Row="2" FontSize="20"/> </Grid>
the output of the MainWindow.xaml is…