Add items to comboBox in WPF

前端 未结 7 1881
谎友^
谎友^ 2021-02-03 21:38

When I have added a comboBox to the WPF window, how do I add items to the comboBox? Int the XAML code for the design or in NameOfWindow.xaml.cs file?

7条回答
  •  一个人的身影
    2021-02-03 22:10

    Scenario 1 - you don't have a data-source for the items of the ComboBox
    You can just populate the ComboBox with static values as follows -
    From XAML:

    
            
            
            
      
    

    Or, from CodeBehind:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        comboBox1.Items.Add("X");
        comboBox1.Items.Add("Y");
        comboBox1.Items.Add("Z");
    }  
    

    Scenario 2.a - you have a data-source, and the items never get changed
    You can use the data-source to populate the ComboBox. Any IEnumerable type can be used as the data-source. You need to assign it to the ItemsSource property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable).

    Scenario 2.b - you have a data-source, and the items might get changed
    You should use an ObservableCollection as the data-source and assign it to the ItemsSource property of the ComboBox (it's up to you how you populate the ObservableCollection). Using an ObservableCollection ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.

提交回复
热议问题