Pages

Monday 23 April 2012

Bindings in Silverlight - Binding to ListBox

Hi, and welcome back.  this is the last post of the Bindings in Silverlight Mini Series .  In this we will see how we can bind data to the ListBox. We will make use of Templates for customising the display.

1) We will write the familiar classes - One for providing us the data and one for the Converter

  public class Vals
    {
        public int val1 { get; set; }
        public int val2 { get; set; }
        public  Vals(int n1,int n2)
        {
        val1 = n1;
        val2 = n2;
        }
    }


    public class MyConv : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int i = Int32.Parse(value.ToString());
            if ( i > 6  &&  i % 5  != 0  &&i  <14  )
            {
                return "Red";
            }
            else if (i < 10)
            {
                return "Blue";
            }
            else
            {
                return "Green";
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


2) Now that we have them in place, lets go and add ListBox to the Xaml , and use an ItemTemplate  to customise it.

 <ListBox Height="345" HorizontalAlignment="Left" Margin="24,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="255" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBox  Background="{Binding Path=val1, Converter={StaticResource myConvStatic} }" Text="{Binding val1}" Width="50"></TextBox>
                        <TextBox Background="{Binding Path=val1, Converter={StaticResource myConvStatic} }" Text="{Binding val2}" Width="50"></TextBox>
                  </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


3)  As you can see , the ItemTemplate of the ListBox contains a DataTemplate tag.  It is the model for how your data should be presented. It can contain only one item , so we use a StackPanel /grid/Canvas  type of structure, to add multiple items .  In case you only want a single item like a textbox, then we can use that directly.

4)   Now add some data to your program in the MainPage constructor
  
           List<Vals> a = new List<Vals>();
            for (int i = 1; i < 10; i++)
            {
                a.Add(new Vals(i*2,i*5));
            }
            listBox1.ItemsSource = a;

Run your program  and you will see the following output.

This ends this Mini Series. Hope you enjoyed the bindings in Silverlight.

No comments:

Post a Comment