katit
katit

Reputation: 17915

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" 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.

Upvotes: 17

Views: 25478

Answers (3)

Parth Shah
Parth Shah

Reputation: 2140

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;

Upvotes: 13

FIre Panda
FIre Panda

Reputation: 6637

Try

string str =  ((ComboBoxItem)this.ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();

in SelectionChanged event handler or in whatever function or event handler.

Upvotes: 2

keyboardP
keyboardP

Reputation: 69372

You need to cast it to a type of ComboBoxItem.

  var selectedTag = ((ComboBoxItem)ExpireAfterTimeComboBox.SelectedItem).Tag.ToString();

Upvotes: 35

Related Questions