Data binding in WPF

Data binding is a technique to establish a connection between the UI of the application and the business logic to have data synchronization between them. Though you can directly access UI controls from code behind to update their content, but data binding became a preferred way to update the UI layer for its autoupdate notification mechanism.

To make data binding work, both the sides of the binding must provide a change notification to the other side. The source property of a data binding can be a normal .NET CLR property or a dependency property, but the target property must be a dependency property:

Data binding is typically done in XAML using the {Binding} markup extension. It can be unidirectional (source > target or target > source) or bidirectional (source < > target), known as Mode and is defined in four categories:

  • OneWay: This type of unidirectional data binding causes the source property to automatically update the target property. The reverse is not possible here. For example, if you want to display a label/text in the UI based on some condition in the code behind or business logic, you need to use OneWay data binding as you don't need to update back the property from the UI:
        <TextBlock Text="{Binding AuthorName}"/> 
        <TextBlock Text="{Binding AuthorName, Mode=OneWay}"/> 
        <TextBox Text="{Binding AuthorName}"/> 
        <TextBox Text="{Binding AuthorName, Mode=OneWay}"/> 
  • TwoWay: This type of binding is a bidirectional data binding, where both the source property and the target property can send update notifications. This is applicable for editable forms where the user can change the value displayed in the UI. For example, the Text property of a TextBox control supports this type of data binding:
        <TextBox Text="{Binding AuthorName, Mode=TwoWay}"/> 
  • OneWay to Source: This is another unidirectional data binding, which causes the target property to update the source property (the reverse of OneWay binding). Here, the UI sends notification to the data context and no notification is generated if the data context changes:
        <TextBox Text="{Binding AuthorName, Mode=OneWayToSource}"/> 
  • One time: This causes the source property to initialize the target property. After that, no notifications will be generated. You should use this type of data binding where the source data does not change.
One way binding is the default data binding.
When you set Mode=OneWay to the Text property of a TextBox, the notification does not generate to the source property if the user updates its value in the UI.

Let's discuss it with a small and simple demonstration. First, create a new WPF project using Visual Studio 2017 and we name it Demo.WPF.DataBinding. It would have already created an XAML file named MainWindow.xaml and MainWindow.xaml.cs.

Open the MainWindow.xaml.cs file and add three dependency properties of type string named AuthorName, BookName, and PublishDate. You can use the propdp snippet to generate the dependency properties. After the addition of the three properties, your code will look like this:

namespace Demo.WPF.DataBinding 
{ 
  public partial class MainWindow : Window 
  { 
    public string AuthorName 
    { 
       get { return (string)GetValue(AuthorNameProperty); } 
       set { SetValue(AuthorNameProperty, value); } 
    } 
 
    public string BookName 
    { 
       get { return (string)GetValue(BookNameProperty); } 
       set { SetValue(BookNameProperty, value); } 
    } 
 
    public string PublishDate 
    { 
       get { return (string)GetValue(PublishDateProperty); } 
       set { SetValue(PublishDateProperty, value); } 
    } 
 
public static readonly DependencyProperty AuthorNameProperty =
DependencyProperty.Register("AuthorName", typeof(string),
typeof(MainWindow), new PropertyMetadata("Kunal Chowdhury")); public static readonly DependencyProperty BookNameProperty =
DependencyProperty.Register("BookName", typeof(string),
typeof(MainWindow), new PropertyMetadata("Mastering Visual Studio")); public static readonly DependencyProperty PublishDateProperty =
DependencyProperty.Register("PublishDate", typeof(string),
typeof(MainWindow), new PropertyMetadata("2017")); public MainWindow() { InitializeComponent(); } } }

Now, as we have three dependency properties already defined, we can start creating the object binding. First, let's give a name mainWindow to the window. This is so as to easily identify the context of the code behind.

Then we need to set the data context of the grid. We can use a data binding here and will tell the grid to use the same class by assigning mainWindow as the element name of the context <Grid DataContext="{Binding ElementName=mainWindow}".

Let's divide the Grid into a few rows, columns, and add few TextBlocks and TextBoxes onto it to complete the data binding steps. Here's the complete code for your reference:

<Window x:Class="Demo.WPF.DataBinding.MainWindow" 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  x:Name="mainWindow" Title="Data Binding Demo"  
  Height="350" Width="700" FontSize="12"> 
  <Grid DataContext="{Binding ElementName=mainWindow}" Margin="20"> 
     <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="Auto"/> 
        <ColumnDefinition Width="20"/> 
        <ColumnDefinition Width="*"/> 
        <ColumnDefinition Width="40"/> 
        <ColumnDefinition Width="Auto"/> 
     </Grid.ColumnDefinitions> 
 
<Grid.RowDefinitions> <RowDefinition Height="26"/> <RowDefinition Height="26"/> <RowDefinition Height="26"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>
<TextBlock Text="Author Name" Grid.Row="0" Grid.Column="0"/> <TextBlock Text=":" Grid.Row="0" Grid.Column="1"
HorizontalAlignment="Center"/> <TextBox Text="{Binding AuthorName, Mode=OneWay}" Grid.Row="0"
Grid.Column="2"/> <TextBlock Text="(Mode=OneWay)" Grid.Row="0" Grid.Column="4"/> <TextBlock Text="Book Name" Grid.Row="1" Grid.Column="0"/> <TextBlock Text=":" Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Center"/> <TextBox Text="{Binding BookName, Mode=TwoWay}" Grid.Row="1"
Grid.Column="2"/> <TextBlock Text="(Mode=TwoWay)" Grid.Row="1" Grid.Column="4"/> <TextBlock Text="Published" Grid.Row="2" Grid.Column="0"/> <TextBlock Text=":" Grid.Row="2" Grid.Column="1"
HorizontalAlignment="Center"/> <TextBox Text="{Binding PublishDate, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="2"/> <TextBlock Text="(Mode=TwoWay, UpdateSourceTrigger=PropertyChanged)"
Grid.Row="2" Grid.Column="4"/> <StackPanel Grid.Row="3" Grid.Column="2" Margin="0 20 0 0"> <TextBlock Text="You entered Author Name:" FontWeight="Bold"/> <TextBlock Text="{Binding AuthorName}"/> <TextBlock Text="You entered Book Name:" FontWeight="Bold"
Margin="0 10 0 0"/> <TextBlock Text="{Binding BookName}"/> <TextBlock Text="You entered Published Date:" FontWeight="Bold"
Margin="0 10 0 0"/> <TextBlock Text="{Binding PublishDate}"/> </StackPanel> </Grid> </Window>

For the first textbox, the Text property has been bound to AuthorName as a OneWay data binding, the second textbox uses a TwoWay data binding mode with the property BookName. The third textbox also uses a TwoWay data binding with the property PublishDate, but has specified UpdateSourceTrigger=PropertyChanged. This tells the system to notify whenever the property changes.

When you build and execute the preceding code, you will see that the following window pops up with a few textblocks and textboxes as defined in the XAML. The values in the textbox controls populate from the default value that we specified at the time of declaring the dependency properties:

Now, modify the text of the first textbox (Author Name) but it will not update the label that we placed below. As it has a OneWay data binding associated with it, no update notification will be sent out even if you trigger a lost focus on that textbox control.

If you change the text of the second textbox (Book Name), no notification will be carried out unless you trigger a lost focus on it. TwoWay data binding will act here to update the associated Textblock automatically.

The third textbox control also has TwoWay data binding associated with it, but it also has a binding property that says, update the source when the property changes. So, if you start typing in the third box, you will see that the Textblock will immediately start getting the notification and update itself:

You can define four set of values to UpdateSourceTrigger and these are as follows:

  • Default: When specified, it triggers based on the default association set by the target. For example, the default trigger for the TextBox.Text property is LostFocus.
  • LostFocus: This gets triggered when the associated control loses its focus.
  • PropertyChanged: This gets triggered when the associated property gets change notification.
  • Explicit: This only gets triggered when the application explicitly calls UpdateSource of the binding.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.118.95