我以前说过,现在再说一遍,WPF 最简单的例子也是最难在网上找到的:)
我有一个组合框,我需要显示,但它不需要数据绑定或其他任何东西,内容是静态的。如何使用 XAML 将项目的静态列表添加到组合框中?
Like this:
<ComboBox Text="MyCombo"> <ComboBoxItem Name="cbi1">Item1</ComboBoxItem> <ComboBoxItem Name="cbi2">Item2</ComboBoxItem> <ComboBoxItem Name="cbi3">Item3</ComboBoxItem> </ComboBox>
Here is the code from MSDN and the link - Article Link, which you should check out for more detail.
<ComboBox Text="Is not open"> <ComboBoxItem Name="cbi1">Item1</ComboBoxItem> <ComboBoxItem Name="cbi2">Item2</ComboBoxItem> <ComboBoxItem Name="cbi3">Item3</ComboBoxItem> </ComboBox>
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:
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"));
<ComboBox Text="Something"> <ComboBoxItem Content="Item1"></ComboBoxItem > <ComboBoxItem Content="Item2"></ComboBoxItem > <ComboBoxItem Content="Item3"></ComboBoxItem > </ComboBox>