gpt4 book ai didi

c# - WPF 组合框值和显示文本

转载 作者:IT王子 更新时间:2023-10-29 04:31:51 27 4
gpt4 key购买 nike

我习惯于做这样的事情

State.Items.Add(new ListItem { Text = "SomeState", Value = NumericIDofState });

State 是 ASP.NET 中的列表框。

如何使用 WPF ComboBox 实现同样的效果?我确实在 ComboBoxItem 对象中看到一个名为“Content”的属性,但是我如何为每个项目分配一个值而不是显示给用户的值?请帮忙。

最佳答案

WPF Combobox有:

  • SelectedValuePath指定路径的属性用于确定 SelectedValue 值的属性属性(property)。它类似于 ASP.NET ListItemValue 属性。
  • DisplayMemberPath定义默认模板的属性描述如何显示数据对象。它类似于 ASP.NET ListItemText 属性。

假设您希望 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" />

SelectedValuePathDisplayMemberPath 属性设置为对象的所需属性名称(KeyValue相应地)由 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com