WPF combobox value and display text

后端 未结 4 1115
無奈伤痛
無奈伤痛 2021-02-12 02:30

I\'m used to doing things like

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

Where State is a Listbox in A

4条回答
  •  不要未来只要你来
    2021-02-12 03:19

    WPF Combobox has:

    • SelectedValuePath property that specifies the path to the property that is used to determine the value of the SelectedValue property. It's similar to ASP.NET ListItem's Value property.
    • DisplayMemberPath property that defines a default template that describes how to display the data objects. It's similar to ASP.NET ListItem's Text property.

    Let's say you want your Combobox to show a collection of the following KeyValuePair objects:

    private static readonly KeyValuePair[] tripLengthList = {
        new KeyValuePair(0, "0"),
        new KeyValuePair(30, "30"), 
        new KeyValuePair(50, "50"), 
        new KeyValuePair(100, "100"), 
    };
    

    You define a property in your view model returning that collection:

    public KeyValuePair[] TripLengthList
    {
        get
        {
            return tripLengthList;
        }
    }
    

    Then, your XAML for the Combobox would be:

    
    

    Where you set SelectedValuePath and DisplayMemberPath properties to the desired property names of the objects (Key and Value correspondingly) displaying by the Combobox.

    Or, if you really want to add items to Combobox in code behind instead of using a binding, you can do it as well. For example:

    
    
    
    // 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(0, "0"));
            this.ComboBoxFrom.Items.Add(new KeyValuePair(30, "30"));
            this.ComboBoxFrom.Items.Add(new KeyValuePair(50, "50"));
            this.ComboBoxFrom.Items.Add(new KeyValuePair(100, "100"));
        }
    

提交回复
热议问题