Get tag of selected item in WPF ComboBox
22,477
Solution 1
You need to cast it to a type of ComboBoxItem
.
var selectedTag = ((ComboBoxItem)ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();
Solution 2
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;
Solution 3
Try
string str = ((ComboBoxItem)this.ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();
in SelectionChanged
event handler or in whatever function or event handler.
Author by
katit
Updated on July 30, 2022Comments
-
katit almost 2 years
I have combobox like this:
<ComboBox Name="ExpireAfterTimeComboBox" Margin="5" SelectedIndex="0"> <ComboBoxItem Content="15 minutes" Tag="15" /> <ComboBoxItem Content="30 minutes" 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.