WPF - 将静态项目添加到组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1791784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - add static items to a combo box
提问by Unknown Coder
I've said it before and I'll say it again, the easiest examples for WPF are also the hardest to find on the web :)
我之前说过,我再说一遍,最简单的 WPF 示例也是最难在网络上找到的 :)
I have a combo box that I need to display but it doesn't need to be databound or anything else, the content is static. How can I add a static list of items to my combo box using XAML?
我有一个需要显示的组合框,但它不需要数据绑定或其他任何内容,内容是静态的。如何使用 XAML 将静态项目列表添加到我的组合框中?
回答by Wade73
Here is the code from MSDN and the link - Article Link, which you should check out for more detail.
这是来自 MSDN 的代码和链接 -文章链接,您应该查看更多详细信息。
<ComboBox Text="Is not open">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
回答by Tony The Lion
Like this:
像这样:
<ComboBox Text="MyCombo">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
回答by omJohn8372
You can also add items in code:
您还可以在代码中添加项目:
cboWhatever.Items.Add("SomeItem");
Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:
此外,要在您控制显示/值的地方添加一些东西(根据我的经验几乎绝对需要),您可以这样做。我在这里找到了一个很好的 stackoverflow 参考:
Key Value Pair Combobox in WPF
Sum-up code would be something like this:
总结代码将是这样的:
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"));
回答by ritesh seth
<ComboBox Text="Something">
<ComboBoxItem Content="Item1"></ComboBoxItem >
<ComboBoxItem Content="Item2"></ComboBoxItem >
<ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>