我习惯于做这样的事情
State.Items.Add(new ListItem { Text = "SomeState", Value = NumericIDofState });
State 是 ASP.NET 中的列表框。
如何使用 WPF ComboBox 实现同样的效果?我确实在 ComboBoxItem 对象中看到一个名为“Content”的属性,但是我如何为每个项目分配一个值而不是显示给用户的值?请帮忙。
最佳答案
-
SelectedValuePath
指定路径的属性 用于确定SelectedValue
值的属性 属性(property)。它类似于 ASP.NETListItem
的Value
属性。 -
DisplayMemberPath
定义默认模板的属性 描述如何显示数据对象。它类似于 ASP.NETListItem
的Text
属性。
假设您希望 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"),
};
您在返回该集合的 View 模型中定义一个属性:
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
属性设置为对象的所需属性名称(Key
和 Value
相应地)由 Combobox
显示。
或者,如果您真的想在代码隐藏中向 Combobox
添加项目而不是使用绑定(bind),您也可以这样做。例如:
<!--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"));
}
关于c# - WPF 组合框值和显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3775514/