Wednesday, October 07, 2009

WPF ComboBox select item when using ItemsSource

I have a WPF ComboBox that is databound to a Linq query.

var mylinqdata = from d in DataTable0.AsEnumerable()


select new


{


Status = d.Field<string>(0).Trim(),


Progress = d.Field<string>(1).Trim()


};


 


dlg.cb_Status.ItemsSource = mylinqdata;




When data is bound to a WPF control using ItemsSource you must change the selected item using SelectedIndex. Here is the code I use.



dlg.cb_Status.SelectedIndex = mylinqdata.ToList().FindIndex(d => d.Status == loom.Status);


Here is the XAML of the ComboBox


<ComboBox Name="cb_Status">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Progress}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

No comments: