WPF - 将静态项添加到组合框

Unk*_*der 80 wpf combobox

我以前说过,我会再说一遍,WPF最简单的例子也是网上最难找到的:)

我有一个我需要显示的组合框,但它不需要数据绑定或其他任何东西,内容是静态的.如何使用XAML将静态项目列表添加到我的组合框?

Wad*_*e73 128

以下是来自MSDN的代码和链接 - 文章链接,您应该查看更多详细信息.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)


Ton*_*ion 20

像这样:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)


omJ*_*372 9

谢谢您的帮助.这对我有帮助.旁注,您还可以在代码中添加项目:

cboWhatever.Items.Add("SomeItem");
Run Code Online (Sandbox Code Playgroud)

此外,要添加控制显示/值的内容(根据我的经验几乎绝对需要),您可以这样做.我在这里找到了一个很好的stackoverflow参考:

WPF中的键值对组合框

总结代码将是这样的:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));
Run Code Online (Sandbox Code Playgroud)