Get tag of selected item in WPF ComboBox
I have combobox like this:
<ComboBox Name="ExpireAfterTimeComboBox" Margin="5" SelectedIndex="0">
<ComboBoxItem Content="15 minutes" Tag="15" />
<ComboBoxItem Content="30 minutes开发者_如何学Python" Tag="30" />
<ComboBoxItem Content="1 hour" Tag="60" />
<ComboBoxItem Content="1 day" Tag="1440" />
</ComboBox>
How do I get Tag value in code?
writing something like ExpireAfterTimeComboBox.SelectedItem.Tag
doesn't work.
You need to cast it to a type of ComboBoxItem
.
var selectedTag = ((ComboBoxItem)ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();
If you could modify your Combobox declaration to the following:
<Combobox Name="ExpireAfterTimeComboBox" Margin="5" SelectedValuePath="Tag">
<ComboBoxItem Content="15 minutes" Tag="15" IsSelected="True" />
<ComboBoxItem Content="30 minutes" Tag="30" />
<ComboBoxItem Content="1 hour" Tag="60" />
<ComboBoxItem Content="1 day" Tag="1440" />
</Combobox>
You could retrieve the tag like so:
var selectedTag = ExpireAfterTimeComboBox.SelectedValue;
Try
string str = ((ComboBoxItem)this.ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();
in SelectionChanged
event handler or in whatever function or event handler.
精彩评论