Saturday, 28 April 2012

Bindings in Silverlight - Bonus post :)

Hi ,
  I was just experimenting with the listbox and combobox ,and decided to combine and use the two together. 
 Effectively,  I want to have a listbox , which contains several combo boxes instead of regular text. 

 And it should all be done with data binding.

So the first step is to create sample data.
 With this requirement in mind, i  decided to create a few classes.

  public class MyObject
        public int Id { get; set; }

  public class encaps
        public List<MyObject> mylist{get;set;}

 As you can see, the data i want to display in the ComboBoxes are integers.  The objects of encaps will be the ItemSource for the Listbox .

We need to bind data to the listbox, and each of that data inturn should be bound to a combo box. So we make use of List<> collection. Create the sample data as shown below.

         List<encaps> l = new List<encaps>();

            for (int j = 0; j < 10; j++)
                List<MyObject> myo = new List<MyObject>();
                for (int i = 0; i < 10; i++)
                    MyObject m = new MyObject();
                    m.Id = i*j;
                encaps e = new encaps();
                e.mylist = myo;

            listBox1.ItemsSource = l;
The second step is to  create Data templates for the listbox and combobox to display the items.   So you need to change the xaml accordingly.

  <ListBox Height="193" HorizontalAlignment="Left" Margin="48,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="325" >
                    <ComboBox ItemsSource="{Binding Path=mylist}" >
                                <TextBlock Width="35"  Height="35" Text="{Binding Path=Id}" />

Observe the bindings here.  The property Id is retrieved from the mylist because the Combobox is exposing that to the TextBlock.    We get our required output, without much effort at all  :)  This can be great for scenarios where you need to show multiple combo boxes . And that's it. We are done .

I haven't changed the width of the combo boxes. You can set them in the Xaml for a nice look and feel.
This same scenario can be done for a data grid also. Just try experimenting and see if it works . All the best :)

No comments:

Post a Comment