WPF - 如何向下拉框中添加静态项目

86

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

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

4个回答

136

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

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

22
就像这样:
<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

9

您也可以在代码中添加项目:

cboWhatever.Items.Add("SomeItem");

此外,如果要控制显示/值(根据我的经验几乎是必需的),可以这样做。我在stackoverflow上找到了一个很好的参考链接:Key Value Pair Combobox in 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"));

3
<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

1
请添加说明,解释你的解决方案为什么能够帮助楼主。 - milo526
我发现知道“Content”属性是在窗体上显示的内容很有帮助,而其他答案(包括我的答案)没有说明。 - omJohn8372

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接