Databinding in Silverlight and WPF

Databinding in SL and WPF are interesting concepts and once mastered really solves many a issues with cleaner code. In XAML everything is dataaware.

Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML.

In this post we will discuss about

  • Simple CLR Object binding using code
  • Simple CLR Binding using XAML only – Demo value converters
  • Control Binding – Slider and textbox
  • Implementing IValueConverter
  • Validation
  • Update Source Trigger
  • StaticResource / DynamicResource

Simple CLR Object binding using code

if we declare a class like below in C# code

   1: public class MyClass

   2:    {

   3:  

   4:        #region ID

   5:        /// <summary>

   6:        /// Gets or sets ID 

   7:        /// </summary>

   8:        public int ID { get; set; }

   9:        #endregion ID

  10:  

  11:  

  12:        #region Name

  13:        /// <summary>

  14:        /// Gets or sets Name 

  15:        /// </summary>

  16:        public string Name { get; set; }

  17:        #endregion Name

  18:  

  19:  

  20:        #region dob

  21:        /// <summary>

  22:        /// Gets or sets dob 

  23:        /// </summary>

  24:        public DateTime dob { get; set; }

  25:        #endregion dob

  26:  

  27:  

  28:    }

   1: public Window1()

   2:        {

   3:            InitializeComponent();

   4:            Validation.AddErrorHandler(txt3, (o, e) =>

   5:                {

   6:  

   7:                    MessageBox.Show((string)e.Error.ErrorContent, "Error");

   8:  

   9:                }

  10:  

  11:                );

  12:  

  13:            DummyData();

  14:        }

  15:  

  16:        public void DummyData()

  17:        {

  18:            MyClass ob = new MyClass() { ID = 1, Name = "abc", dob = new DateTime(1980, 06, 08) };

  19:            this.DataContext = ob;

  20:  

  21:        }

we can simply bind it by using following

<StackPanel DataContext={Binding}>

        <TextBox x:Name="txt1" Text="{Binding Path=Name}" ></TextBox>

</StackPanel>

Simple CLR Binding using XAML only

We can just use XAML to declare variables of the class and use databinding as below

   1: <Window.Resources>

   2:         <local:MyClass x:Key="ob1" ID="1" Name="abc"></local:MyClass>

   3:         <local:MyClass x:Key="ob2" ID="2" Name="Red1"></local:MyClass>

   4:  

   5:     </Window.Resources>

   6:    <StackPanel>

   7:         <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=OneWay}"></TextBox>

   8:         <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=OneWay}"></TextBox>

   9:     </StackPanel>

the output is:

image

Similar to setting “text” property we may even set “Background” to the text peoperty like below:

<TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                 ></TextBox>

the output changes to: :D. the name of color is also the background!!!

image

Notice as i write and into text box and then click else where the color also changes as below:

image

What will happen if i give a improper color name? An exception? WPF and SL gives into trace message in case something goes wrong with databining. IT DOES NOT GIVES AN EXPLICIT EXCEPTION. like below

image

Notice that there is a trace in output window stating that there is no color “Subodh” however, it does not give an error on UI.

If i want a Blue color everytime i write “Subodh”, then i can write a Converter.

Value converters

   1: public class MyValueConverter : IValueConverter

   2:     {

   3:  

   4:         #region IValueConverter Members

   5:  

   6:         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   7:         {

   8:             string str = (string)value;

   9:             if (!string.IsNullOrEmpty(str))

  10:             {

  11:                 if (str == "Subodh")

  12:                 {

  13:                     return new SolidColorBrush(Colors.Blue);

  14:                 }

  15:             }

  16:             return value;

  17:         }

  18:  

  19:         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  20:         {

  21:             throw new NotImplementedException();

  22:         }

  23:  

  24:         #endregion

  25:     }

When this Converter is used in XAML, whenever is write “subodh” background will be blue. But for that i have declare the converter in XAML also like:

<Window.Resources>

        <local:Person x:Key="ob1" ID="1" Name="Subodh"/>

        <local:Person x:Key="ob2" ID="2" Name="Yellow"/>

        <local:MyValueConverter x:Key="myValueConverter"></local:MyValueConverter>

    </Window.Resources>

    <StackPanel Background="{DynamicResource solidColorBrush}">

        <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name, Converter={StaticResource myValueConverter}}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                ></TextBox></StackPanel>

output:

image 

Control Binding:

We can bind two controls to each other value using XAML only code like:

if we define something like below.

<StackPanel>

            <ListBox x:Name="lst1" ItemsSource="{Binding Source={x:Static Sys:DateTimeFormatInfo.CurrentInfo}, Path=MonthNames}"></ListBox>

            <TextBox Text="{Binding ElementName=lst1, Path=SelectedItem}"></TextBox>

        </StackPanel>

for the above you may need

xmlns:Sys="clr-namespace:System.Globalization;assembly=mscorlib"

then the output is like :

image

Notice how we are binding MonthNames and then each selected item is displayed in the textbox… All using XAML!!!

If i require the list box items change according to the textbox at runtime and vice versa then i need to inherit my datasource using ObservableCollection as

   1: /// <summary>

   2:     /// Interaction logic for Window2.xaml

   3:     /// </summary>

   4:     public partial class Window2 : Window

   5:     {

   6:         public Window2()

   7:         {

   8:             InitializeComponent();

   9:             personTeam = new PersonTeam() { new Person() { ID = 1, Name = "sdS" }, new Person() { ID = 2, Name = "def" } };

  10:             this.DataContext = personTeam;

  11:         }

  12:         PersonTeam personTeam;

  13:         private void Button_Click(object sender, RoutedEventArgs e)

  14:         {

  15:             personTeam.Add(new Person() { ID = 1, Name = "zzz" }); ;

  16:         }

  17:     }

  18:  

  19:     public class PersonTeam : ObservableCollection<Person>

  20:     { 

  21:         

  22:     }

Now in XAML i may write

   1: <StackPanel DataContext="{Binding}">

   2:            <ListBox x:Name="lst2" ItemsSource="{Binding}">

   3:                <ListBox.ItemTemplate>

   4:                    <DataTemplate>

   5:                        <TextBox Text="{Binding Path=Name, Mode=TwoWay}"></TextBox>

   6:                    </DataTemplate>

   7:                </ListBox.ItemTemplate>

   8:            </ListBox>

   9:            <TextBox Text="{Binding ElementName=lst2, Path=SelectedItem.Name, UpdateSourceTrigger=PropertyChanged }"></TextBox>

  10:            <!--<Button Content="Add" Click="Button_Click"></Button>-->

  11:        </StackPanel>

here are the effects

image

Whenever i change something in either of the test box; the value changes in both!!!

I will blog the validations part in the next series.

Here is the code for the above and the ppt slides.

Please let me know you thoughts / comments.

Technorati Tags: ,
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s