WPF Combobox 有:
假设您希望您的 Combobox 显示以下 KeyValuePair 对象的集合:
private static readonly KeyValuePair<int, string>[] tripLengthList = {
new KeyValuePair<int, string>(0, "0"),
new KeyValuePair<int, string>(30, "30"),
new KeyValuePair<int, string>(50, "50"),
new KeyValuePair<int, string>(100, "100"),
};
您在返回该集合的视图模型中定义一个属性:
public KeyValuePair<int, string>[] TripLengthList
{
get
{
return tripLengthList;
}
}
那么,Combobox 的 XAML 将是:
<ComboBox
SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}"
ItemsSource="{Binding TripLengthList, Mode=OneTime}"
SelectedValuePath="Key"
DisplayMemberPath="Value" />
您将SelectedValuePath 和DisplayMemberPath 属性设置为Combobox 显示的对象(对应的Key 和Value)的所需属性名称。
或者,如果你真的想在后面的代码中将项目添加到Combobox,而不是使用绑定,你也可以这样做。例如:
<!--XAML-->
<ComboBox x:Name="ComboBoxFrom"
SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}" />
// Code behind
public partial class FilterView : UserControl
{
public FilterView()
{
this.InitializeComponent();
this.ComboBoxFrom.SelectedValuePath = "Key";
this.ComboBoxFrom.DisplayMemberPath = "Value";
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(0, "0"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(30, "30"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(50, "50"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(100, "100"));
}