Thursday 21 August 2014

Simple Databinding in silverlight

Here we will do simple data binding in a Silverlight application Different types of binding modes available and how to use them declaratively and programmatically. We will also see how to do binding for a collection, the importance of the INotifyPropertyChanged interface method, and the ObservableCollection class.

There are three types of data binding that happens in Silverlight applications between a source and target.

OneTime data binding: As the name suggests, data binding happens between the source and target only once. In this binding, the source (CRL object) data will bind with the target (XAML element) only when the page executes the first time. Later on, any changes made in the source will not be reflected back in the target element. You will prefer to use this binding mode to reduce overhead if you know that the source property won’t change.
OneWay data binding: In this data binding, the source will immediately inform about changes to the target control. We will be using this binding only for frequently changed elements. This is the default mode.
TwoWay data binding: This happens in bidirectional mode. Whenever any change occurs in the backend or the CRL object, it will inform to the XAML controls immediately, and vice versa. 

The binding statement has many properties, but here is a list of frequently used properties of the Binding statement:

Path is the name of the source property to get the data from.
Mode is the connection type (OneTime, OneWay, and TwoWay) between the source and the target.
Source is the standard CLR object that contains the data.
Converter is used to specify the converter object that is called by the binding engine to modify the data as it is passed between the source and the destination.
Converter Culture specifies a parameter that can be passed to the conversion of the data.
Conversion Parameter specifies a parameter that can be passed to the converter.

There is one more important thing in database binding, which is the DataContext property. The DataContextproperty is used to set or get the data context for a FrameworkElement when it is participate in data binding.
Data context is inherited. If you set the data context on a parent element, all its children will use the same data context. A child element can override this behavior by setting the Source property on its binding object or by setting itsDataContext, which will then apply to all its children.
The DataContext property can be set in the parent control or for each child control. The only advantage of setting it in the parent control is, you don’t need to repeat it for each child control.

* Create Class name it as Customer :



namespace DataContextBinding
{
    public class Customer
    {
        private string _fname;

        public string Fname
        {
            get { return _fname; }
            set { _fname = value; }
        }
        private string _lname;

        public string Lname
        {
            get { return _lname; }
            set { _lname = value; }
        }
        private string _emailid;

        public string Emailid
        {
            get { return _emailid; }
            set { _emailid = value; }
        }
    }
}

*in you MainPage.Xaml


<UserControl x:Class="DataContextBinding.MainPage"
             xmlns:local="clr-namespace:DataContextBinding"
    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"
    mc:Ignorable="d"
    >
    <UserControl.Resources>
        <local:Customer x:Key="employeeInfo" Fname="shoeb" Lname="ahmed" Emailid="skshoeb26@gmail.com"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot"
      DataContext="{StaticResource employeeInfo}"
       Width="500" Height="300"
       >
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Text="First Name" Grid.Column="1" Grid.Row="1"></TextBlock>
        <TextBox x:Name="txtFirstName" Text="{Binding Path=Fname, Mode=OneTime}"
                 Grid.Column="2" Grid.Row="1"></TextBox>

        <TextBlock Text="Last Name" Grid.Column="1" Grid.Row="2"></TextBlock>
        <TextBox x:Name="txtLastName" Text="{Binding Path=Lname, Mode=OneTime}"
                 Grid.Column="2" Grid.Row="2"></TextBox>

        <TextBlock Text="Email ID" Grid.Column="1" Grid.Row="3"></TextBlock>
        <TextBox x:Name="txtEmailID" Text="{Binding Path=Emailid, Mode=OneTime}"
                 Grid.Column="2" Grid.Row="3"></TextBox>
    </Grid>
</UserControl>


Binding can also be performed programmatically. What you need to do is just create a new binding object and call the SetBinding() method to perform the binding between the source and the target

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;


namespace DataContextBinding
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Customer cs = new Customer();
            cs.Fname = "shoeb";
            cs.Lname = "ahmed";
            cs.Emailid = "skshoeb26@gmail.com";
            Binding b = new Binding()
            {
                Source = cs,
                Path = new PropertyPath("Emailid"),
                Mode = BindingMode.OneTime
            };
            Binding b1 = new Binding()
            {
                Source = cs,
                Path = new PropertyPath("Fname"),

                Mode = BindingMode.OneTime
            };
            Binding b2 = new Binding()
            {
                Source = cs,
                Path = new PropertyPath("Lname"),
                Mode = BindingMode.OneTime
            };
            txtFirstName.SetBinding(TextBox.TextProperty, b);
            txtLastName.SetBinding(TextBox.TextProperty, b1);
            txtEmailID.SetBinding(TextBox.TextProperty, b2);
        }

    }
}

ObservableCollection:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace BasicBinding
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            this.Loaded +=new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.grid.ItemsSource = DataGrid.GetData();
        }
    }
    public class DataGrid : INotifyPropertyChanged
    {
        private string _name;
        private int _age;
        private bool _male;

        public string Name
        {
            get { return _name; }
            set { _name = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Name"));
            }
        }


        public int Age
        {
            get { return _age; }
            set { _age = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Age"));
            }
        }


        public bool Male
        {
            get { return _male; }
            set { _male = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Male"));
            }
        }
        public static ObservableCollection<DataGrid> GetData()
        {
          
            ObservableCollection<DataGrid> data = new ObservableCollection<DataGrid>();
            data.Add(new DataGrid() {
                Name="shoeb",
                Age=24,
                Male=true
            });
            data.Add(new DataGrid() {
                Name="abdul",
                Age=25,
                Male=true,

            });
            data.Add(new DataGrid() {
                Name="liza",
                Age=22,
                Male=false
            });
            return data;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }
    }
}



<UserControl
    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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    xmlns:data="clr-namespace:BasicBinding"
    x:Class="BasicBinding.MainPage"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
        <Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid Name="grid" Margin="10" >
        </sdk:DataGrid>
    </Grid>
</UserControl>


In my next article i will show you how to use ObservableCollection in combination with an object implementing INotifyPropertyChanged interface to display live data in Silverlight Application...

No comments:

Post a Comment