设置 ComboBox 项目标签

CBr*_*eze 1 c# wpf combobox

我是这样添加的ComboBoxItems

foreach (var cntRef in presetList.Where(filteredPreset => filteredPreset.PresetReferenceFoxPro == 1).ToList())
{
    var newItem = new ComboBoxItem();
    newItem.Content = cntRef.PresetText;
    newItem.Tag = cntRef.PresetIDFoxPro;
    addCntRef1ComboBox.Items.Add(newItem);
}
Run Code Online (Sandbox Code Playgroud)

这样显示文字没问题。但是我在显示Tag. 当我尝试访问时Tag

if (addCntRef1ComboBox.Tag.ToString() != null)
{
    MessageBox.Show(addCntRef1ComboBox.Tag.ToString());
}
Run Code Online (Sandbox Code Playgroud)

什么都不显示。当我删除null检查程序崩溃时,显然Tagnull. 如何添加ComboBoxItem一个tag我可以访问?

Ark*_*z K 5

您正在将标签实例分配给ComboBoxItemComboBox实例。

newItem.Tag = cntRef.PresetIDFoxPro;
Run Code Online (Sandbox Code Playgroud)

并且newItemComboBoxItem实例,但是您正在尝试TagaddCntRef1ComboBox变量中访问属性

MessageBox.Show(addCntRef1ComboBox.Tag.ToString());
Run Code Online (Sandbox Code Playgroud)

因此程序行为正确。

您需要访问具体的ComboBoxItem你在Item组合框的集合,就像这样:

MessageBox.Show(addCntRef1ComboBox.Items[0].Tag.ToString());
Run Code Online (Sandbox Code Playgroud)