I have a combo box like this
<ComboBox Name="myMenu">
<ComboBoxItem Content="Question 1" Tag="1" />
<ComboBoxItem Content="Question 2" Tag="2" />
<ComboBoxItem Content="Question 3" Tag="3" />
<ComboBoxItem Content="Question 4" Tag="4" />
</ComboBox>
How can I programmatically set the selected index by Tag Value? E.g. ‘myMenu.selectedTag = 3’ and Question 3 would be the selected item?
I want something easier than my current solution really…
int tagToSelect = 3;
foreach (ComboBoxItem item in myMenu.Items)
{
if(item.Tag.Equals(tagToSelect)
{
myMenu.SelectedItem = item;
}
}
Looks like you’re looking for the proeprty SelectedValuePath of ComboBox control. See example here http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectedvaluepath.aspx
For those people who cannot find example under the link above and keep downvoting I prepared my own example. It highlights how to setup ComboBox and select appropriate item by assigning selected value.
MainWindow.xaml
MainWindow.xaml.cs