Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • DataBinding in WPF

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 278
    Comment on it

    Hello Readers,

    Data Binding is a concept which is used to bring/display data in UI controls from source object. DataBinding in WPF is binding between the source object and the destination UI element. With data binding in WPF you can take data from almost any property of any object and bind it to almost any other dependency property of another object. The advantage of using DataBinding in WPF is that when the source changes, the destination property will automatically be updated once binding has occurred. In WPF, binding is very cleaner and easier to maintain. In other words, binds two data source and maintains the synchronization of data between them.

    A simple binding look like this:
    {Binding}
    This simply returns the current data context. If you want to bind a property to another property on the data context. A binding would look like this:
    {Binding Path=NameOfProperty}
    The Path notes the property that you want to bind to, however, since Path is the default property of a binding, you may leave it out if you want to, like this:
    {Binding NameOfProperty}

    A binding has many other properties. They are:
    Converter - Sets the converter to be used.
    ElementName - The name of the element to which the binding is to be made.
    FallbackValue - Sets the value to use when binding cannot return a value.
    Mode - Sets the direction of the binding.
    Path - The path to the element property being used as the data source.
    RelativeSource - Sets the binding source by specifying an element relative to the current element.
    Source - The source object to use for binding.
    StringFormat - Specifies the format of the string representation of a value if the element is bound to a string property.
    UpdateSourceTrigger - Sets the events on which binding will occur.
    ValidationRules - A collection of the validation rules applied against a binding.

    Each property that we set in the binding is separated by a comma(,) for example -
    {Binding Path=Text, ElementName=txtValue}

    where txtValue is name of element and Text is the property of control.

    DataBinding is of two types − one-way data binding and two-way data binding.

    1. One-Way Data Binding: In this binding, data bounds from source to destination.
       
    2. Two-Way Data Binding: In this binding, Changes to source and destination are copied to each other that is if the user modify the data through the user interface and have that data updated in the source and vice-versa.

    To understand the above mentioned bindings, create a new WPF project with the name DataBindingInWPF

    MainWindow.xaml.cs

    using System.Windows;
    
    namespace DataBindingInWPF
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            Manipulation sumOfNumbers = new Manipulation { Num1 = 5, Num2 = 5 };
    
            public MainWindow()
            {
                InitializeComponent();
                this.DataContext = sumOfNumbers;
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                string message = "The total is " + (sumOfNumbers.Num1 + sumOfNumbers.Num2);
                MessageBox.Show(message);
            }
        }
    
        public class Manipulation
        {
            private int num1;
            public int Num1
            {
                get { return num1; }
                set { num1 = value; }
            }
    
            private int num2;
            public int Num2
            {
                get { return num2; }
                set { num2 = value; }
            }
        }
    }

    MainWindow.xaml for One-way DataBinding

    <Window x:Class="DataBindingInWPF.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:DataBindingInWPF"
            mc:Ignorable="d"
            Title="Sum Of Numbers" Height="150" Width="350">
        <Grid>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height = "Auto" />
                    <RowDefinition Height = "Auto" />
                    <RowDefinition Height = "*" />
                </Grid.RowDefinitions>
    
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width = "Auto" />
                    <ColumnDefinition Width = "200" />
                </Grid.ColumnDefinitions>
    
                <Label Name = "firstNumberLabel" Margin = "2">First Number:</Label>
                <TextBox Name = "firstNumberText" Grid.Column = "1" Margin = "2" Text = "{Binding Num1, Mode = OneWay}"/>
    
                <Label Name = "secondNumberLabel" Margin = "2" Grid.Row = "1">Second Number:</Label>
                <TextBox Name = "secondNumberText" Grid.Column = "1" Grid.Row = "1" Margin = "2" Text = "{Binding Num2, Mode = OneWay}"/>
    
                <StackPanel Grid.Row = "2" Grid.ColumnSpan = "2">
                    <Button Content = "Show Total" Click="Button_Click" />
                </StackPanel>
    
            </Grid>
        </Grid>
    </Window>
    

    In above mentioned code, When you press the Show Total button, it will display the total of numbers i.e. "The total is 10". The result will not change if you manually change the of First Number and Second Number text boxes.

     

    MainWindow.xaml for Two-way DataBinding

    <Window x:Class="DataBindingInWPF.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:DataBindingInWPF"
            mc:Ignorable="d"
            Title="Sum Of Numbers" Height="150" Width="350">
        <Grid>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height = "Auto" />
                    <RowDefinition Height = "Auto" />
                    <RowDefinition Height = "*" />
                </Grid.RowDefinitions>
    
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width = "Auto" />
                    <ColumnDefinition Width = "200" />
                </Grid.ColumnDefinitions>
    
                <Label Name = "firstNumberLabel" Margin = "2">First Number:</Label>
                <TextBox Name = "firstNumberText" Grid.Column = "1" Margin = "2" Text = "{Binding Num1, Mode = TwoWay}"/>
    
                <Label Name = "secondNumberLabel" Margin = "2" Grid.Row = "1">Second Number:</Label>
                <TextBox Name = "secondNumberText" Grid.Column = "1" Grid.Row = "1" Margin = "2" Text = "{Binding Num2, Mode = TwoWay}"/>
    
                <StackPanel Grid.Row = "2" Grid.ColumnSpan = "2">
                    <Button Content = "Show Total" Click="Button_Click" />
                </StackPanel>
    
            </Grid>
        </Grid>
    </Window>
    

    In above mentioned code, When you press the Show Total button, it will display the total of numbers i.e. "The total is [sum of first number and second number]".

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: