Get tag of selected item in WPF ComboBox

梦想与她 提交于 2019-12-30 07:56:40

问题


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.


回答1:


You need to cast it to a type of ComboBoxItem.

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



回答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;



回答3:


Try

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

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



来源:https://stackoverflow.com/questions/6309495/get-tag-of-selected-item-in-wpf-combobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!