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

标签 c# .net wpf visual-studio-2010

我习惯于做这样的事情

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/

相关文章:

c# - Quartz.net 取消 token

.net - Linq2Sql 更新

c# - 不同的行为取决于缓冲区的大小

c# - 为什么将 DateTime 格式化为字符串会截断而不是舍入毫秒?

c++ - 我的 DirectX 游戏引擎的 WPF 世界编辑器

c# - asp.net gridview 不显示数据

C# Mysql cultureinfo.invariantculture

c# - 您可以将内联值与 AutoFixture 中的 AutoData 结合起来吗?

c# - 在 WPF 中,如何区分列表框项目或滚动条中的鼠标点击

wpf - MVVM 多 View