Add comboBox items from code behind. [WPF]

前端 未结 3 1089
一整个雨季
一整个雨季 2021-01-12 19:06

I grabbed this code from MSDN. What Im trying to do is similar, but use a list instead of three different strings. so say

List strList = new Li         


        
相关标签:
3条回答
  • 2021-01-12 19:50

    You can use data binding. Data binding allows you to bind the dynamic data from your list to the combobox and have it generated and filled with the content you are passing through.

    Binding WPF Combobox to a Custom List

    0 讨论(0)
  • 2021-01-12 19:55

    Set the items programmatically:

    Code-behind:

        private void PopulateComboBox()
        {
            cBox.ItemsSource = new List<string> { "Item1", "Item2", "Item3"};
        }
    

    XAML:

    <ComboBox Width="200" Height="30"  x:Name="cBox" />
    

    Bind to a collection of items:

        public class DummyClass
        {
            public int Value { get; set; }
            public string DisplayValue { get; set;}
        }
    
        public ObservableCollection<DummyClass> DummyClassCollection
        {
            get
            {
                return new ObservableCollection<DummyClass>
                {
                    new DummyClass{DisplayValue = "Item1", Value = 1},
                    new DummyClass{DisplayValue = "Item2", Value = 2},
                    new DummyClass{DisplayValue = "Item3", Value = 3},
                    new DummyClass{DisplayValue = "Item4", Value = 4},
                };
            }
        }
    

    XAML:

    <ComboBox Width="200" Height="30"  x:Name="cBox" ItemsSource="{Binding DummyClassCollection}" DisplayMemberPath="DisplayValue" />
    
    0 讨论(0)
  • 2021-01-12 20:00

    If you don't want to do this following a binding/mvvm pattern, it is quite simple to just do the following:

    foreach (var item in items)
    {
        _comboBox.Items.Add(item);
        _comboBox.SelectedValuePath = "ID";
        _comboBox.DisplayMemberPath = "Name";
    }
    

    Which can be accessed later like so:

    var id = _comboBox.SelectedValue;
    
    0 讨论(0)
提交回复
热议问题