Home > front end >  How to get selected item's Tag in ComboBox?
How to get selected item's Tag in ComboBox?

Time:02-05

I have an ComboBox that contains some items that have a Tag, which I need to associated them to the database (Tag contains Id in database), but I don't know how to get the it. I tried this but it doesn't work. It says you can't convert string to ComboBox.

var cbi = (ComboBoxItem)PropertyTemplateList.SelectedItem;

var Id = Convert.ToInt64(cbi.Tag);

CodePudding user response:

You can ask the ItemContainerGenerator of the ComboBox for the item container, a ComboBoxItem.

var item = PropertyTemplateList.SelectedItem;
var cbi = (ComboBoxItem)PropertyTemplateList.ItemContainerGenerator.ContainerFromItem(item);

if (cbi is null)
{
   // ...handle nothing selected.
   return;
}
else
{
   var Id = Convert.ToInt64(cbi.Tag);

   // ...do something.
   return;
}

This works both for binding an ItemsSource and hardcoded ComboBoxItems.

CodePudding user response:

 var cbi = PropertyTemplateList.SelectedIndex;
 ComboBoxItem comboitem = (ComboBoxItem)PropertyTemplateList.Items[cbi];
 var id = Convert.ToInt64(comboitem.Tag);
  •  Tags:  
  • Related