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);
>Solution :
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.