by JBrooks
6. May 2011 07:13
Some things in Silverlight seem harder than they should be. Binding a list of strings to a combobox is one such thing. This involves the following steps to do a simple bind.
1. Have a private list of the strings in your page code.
private List<string> FuelList = new List<string>()
{
"OIL",
"GAS",
"COAL"
};
2. In your initialization method add the list as a resource so your XAML can use it. This must be done before the InitializeComponent(); call.
public ucMyUserControl()
{
this.Resources.Add("FuelList", FuelList);
InitializeComponent();
}
3. Then you can reference the list as the source to you combo box.
<sdk:DataGrid AutoGenerateColumns="False" MinHeight="130" Name="dgMyDataGrid"
ItemsSource="{Binding Path=ScheduleRows, Mode=TwoWay}"
CurrentCellChanged="dgMyDataGrid_CurrentCellChanged">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Fuel Type">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Margin="2" VerticalAlignment="Center"
HorizontalAlignment="Left" Text="{Binding FUEL_TYPE}" Width="120" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
<sdk:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox Height="23" Name="cbxFuelType"
ItemsSource="{StaticResource FuelList}"
SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120">
</ComboBox>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
...
4. One last item, notice the datagrid’s current cell changed event is wired up to start editing without requiring the user to click first. That method is simple enough:
private void dgMyDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
dgMyDataGrid.BeginEdit();
}
That gives me my datagrid with my combo box:
Here is a sample solution that has the full code:
ComboBoxTest.zip (1,016.17 kb)
a91afe6c-2dc2-46ec-a827-0bfeaf1690b4|5|5.0|27604f05-86ad-47ef-9e05-950bb762570c
Tags:
Development | Silverlight