Tuesday, December 14, 2010

SilverLight - Fill a ComboBox


Just doing some test

Binding a ComboBox at runtime.
private void button1_Click(object sender, RoutedEventArgs e)
{
List<Car> carList = new List<Car>();
carList.Add(new Car() { Name = "Ferrari", Price = 150000 });
carList.Add(new Car() { Name = "Honda", Price = 12500 });
carList.Add(new Car() { Name = "Toyota", Price = 11500 });
comboBox1.ItemsSource = carList;
comboBox1.DisplayMemberPath = "Name";
comboBox1.SelectedIndex = 2;
comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}
void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Car selCar =(Car) comboBox1.SelectedItem;
MessageBox.Show(selCar.Name);
}
}
public class Car
{
public string Name { get; set; }
public int Price { get; set; }
}

Binding a ComboBox at design time;
<ComboBox Height="23" HorizontalAlignment="Left" Margin="225,184,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" >
            <ComboBoxItem Content="Value-1"></ComboBoxItem>
            <ComboBoxItem Content="Value-2"></ComboBoxItem>
            <ComboBoxItem Content="Value-3"></ComboBoxItem>
            <ComboBoxItem Content="Value-4"></ComboBoxItem>
            <ComboBoxItem Content="Value-5"></ComboBoxItem>
</ComboBox>

No comments:

Post a Comment