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


82

我已经说过了,我会再说一遍,最简单的WPF示例也是在网络上最难找到的:)

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

Answers:


131

这是来自MSDN的代码和链接-Article Link,您应该查看更多详细信息。

<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>

10

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

cboWhatever.Items.Add("SomeItem");

另外,可以添加一些东西来控制显示/值(在我的经验中几乎绝对需要),您可以这样做。我在这里找到了很好的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"));

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

1
请也添加信息,为什么您的解决方案可能会帮助OP
milo526
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.