C#

How Data Binding Works in WPF

In general, Data Binding is a way to communicate the data among the code and UI components. Today I will explain How Data Binding Works in WPF (Windows Presentation Foundation). In order to get familiar with WPF, you can go through this basic article on WPF. While creating a navigation window application in WPF is explained here.

To begin with, let us first discuss the concept of data binding. Basically, data binding provides a mechanism that keeps the business logic and UI elements separate while allowing the application to interact with data. In fact, UI elements can fetch data from a variety of sources. Whenever, the application uses data binding, any change in the data source is reflected instantly in UI elements.

Data binding has four elements. The first one is the target object. For instance, if a TextBox displays the data, then TextBox is the target object. The second one is the target property. For example, Text is the target property in the case of a TextBox. The third one is the source object. For instance, the code contains a class called Student, then the object of this class is called the source object. Finally, the fourth one is the source value. In this example, the source value is the Name in the Student object.

The Types of Data Binding in WPF

The following four types of Data Binding are possible in a WPF application.

  1. One Way Binding
  2. Two Way Binding
  3. One Time Binding
  4. One Way to Source Binding

One Way Binding

Whenever any change occurs in the source property, the same is instantly applies to the target property value. However, the reverse is not true. In other words, changing the value of the target property value doesn’t affect the source property.

Two Way Binding

In contrast to the One Way Binding, in Two Way Binding, the changes are bidirectional. Hence any change in either the source property or in the target property will cause an instant change in the other one.

One Time Binding

In like manner to the One Way Binding, the One Time Binding also propagates the changes from the source property to the target property value. However, it does so only once at the time of initialization. Further changes in the source property value don’t change the target property value.

One Way to Source Binding

Analogous to the One Way Binding, the One Way to Source Binding also causes the updates to take place in one direction. However, now it is from the target to the source. Therefore, whenever the target property value changes, the same is reflected in the source. While the same doesn’t happen in the reverse direction.

Examples of Data Binding

The following examples demonstrate How Data Binding Works in WPF. In general, all the examples will use the following class.

public partial class MainWindow : Window
    {
        Numbers ob = new Numbers {X=35, Y=97 };
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = ob;
        }

        private void findsum(object sender, RoutedEventArgs e)
        {
            String msg = $"Sum of {ob.X} and {ob.Y} is {ob.Sum}";
            MessageBox.Show(msg);
        }
    }
    class Numbers
    {
        int x, y, sum;
        public int X
        {
            get
            {
                return x;
            }
            set
            {
                x = value;
            }
        }
        public int Y
        {
            get
            {
                return y;
            }
            set
            {
                y = value;
            }
        }
        public int Sum
        {
            get
            {
                return x + y;
            }
        }

    }

Example of One Way Binding

<Window x:Class="WpfApp4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="Data Binding Example" Height="350" Width="450">
    <Grid Margin="10,10,10,10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Margin="2,2,2,2" Grid.Row="0" Grid.Column="0" 
               Grid.ColumnSpan="2" Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Center">Sum of Two Numbers</Label>
        <Label Margin="2,2,2,2" Grid.Row="1" Grid.Column="0" 
               Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left">First Number: </Label>
        <Label Margin="2,2,2,2" Grid.Row="2" Grid.Column="0" 
               Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left">Second Number:</Label>
        <TextBox Margin="2,2,2,2" Grid.Row="1" Grid.Column="1" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left" Width="200" Name="t1" 
                 Text="{Binding X, Mode=OneWay}"
                 />
        <TextBox Margin="2,2,2,2" Grid.Row="2" Grid.Column="1" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left" Width="200"
                 Name="t2" Text="{Binding Y, Mode=OneWay}"/>
        <Button Margin="2,2,2,2" Grid.Row="3" Grid.Column="0" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
                Grid.ColumnSpan="2"
               HorizontalAlignment="Center" Width="200" Height="40"
                Content="Find Sum" Click="findsum"/>
    </Grid>
</Window>

Output

 Example of One Way Data Binding
Example of One Way Data Binding

Example of Two Way Binding

The following example shows a Two Way Binding in which changing the values of the properties X and Y occur when we change the data in the corresponding TextBox. Also, the values from the properties also get transferred to the corresponding TextBox.

<Window x:Class="WpfApp4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="Data Binding Example" Height="350" Width="450">
    <Grid Margin="10,10,10,10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Margin="2,2,2,2" Grid.Row="0" Grid.Column="0" 
               Grid.ColumnSpan="2" Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Center">Sum of Two Numbers</Label>
        <Label Margin="2,2,2,2" Grid.Row="1" Grid.Column="0" 
               Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left">First Number: </Label>
        <Label Margin="2,2,2,2" Grid.Row="2" Grid.Column="0" 
               Background="Beige" 
               Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left">Second Number:</Label>
        <TextBox Margin="2,2,2,2" Grid.Row="1" Grid.Column="1" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left" Width="200" Name="t1" 
                 Text="{Binding X, Mode=TwoWay}"
                 />
        <TextBox Margin="2,2,2,2" Grid.Row="2" Grid.Column="1" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
               HorizontalAlignment="Left" Width="200"
                 Name="t2" Text="{Binding Y, Mode=TwoWay}"/>
        <Button Margin="2,2,2,2" Grid.Row="3" Grid.Column="0" 
                 Background="Beige" Foreground="DarkBlue" FontSize="20" 
                Grid.ColumnSpan="2"
               HorizontalAlignment="Center" Width="200" Height="40"
                Content="Find Sum" Click="findsum"/>
    </Grid>
</Window>

Output

Demonstration of Two Way Binding
Demonstration of Two Way Binding


Related Topics

A Beginner’s Tutorial on WPF in C#

Everything about Tuples in C# and When to Use?

Linear Search and Binary Search in C#

Creating Jagged Arrays in C#

Learning Indexers in C#

Understanding Method Parameter Modifiers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Practice Questions

C# Basic Examples

Private and Static Constructors in C#

Constructors in C#

C# Arrays

C# Examples

How to Create a C# Console Application

Creating Navigation Window Application Using WPF in C#

LINQ To SQL Examples

Understanding the Concept of Nested Classes in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Examples of Extension Methods in C#

Learning All Class Members in C#

Access Modifiers in C#

C# Root Class – Object

KeyValuePair and its Applications

IEnumerable and IEnumerator Interfaces

IEqualityComparer Interface

New Features in C# 9

Generic IList Interface and its Implementation in C#

Examples of Connected and Disconnected Approach in ADO.NET

Leave a Reply

Your email address will not be published. Required fields are marked *