WPF - Setting the ComboBox Item Index and Item Value via LINQ Anonymous Types
I want to retrieve data from 2 columns of my database table and bind those 2 columns to the combobox item index and item value properties respectively. I retrieve my data from the samples table of my database with this anonymous query:
var result = from obj in context.Samples
select new { obj.ID , obj.Name };
I want to set the default index value of each item in my combobox to obj.ID
and the value of each respective combobox item to obj.Name
so that rather than the items in my combo box having default values starting from 0, 1, 2.... their index values will have the value of obj.ID
returned by my LINQ query and the actual value of the item will be obj.Name
.
Sorry if this is a silly/amateurish question but I've spent a few hours trying to fix it and had no luck. Thanks in advance.
The SelectedIndex
property always goes from -1
(no item is selected) to count-1
, you can't change that. If you want to store the ID
and Name
for each item in the ComboBox
, you can do that:
Create non-anonymous type Sample
that contains those two properties. Then assign (or bind) collection of Sample
s to the ComboBox
's ItemSource
and set DisplayMemberPath
toName
. Then you can access the ID
of the selected item using ((Sample)yourComboBox.SelectedItem).ID
.
精彩评论