wpfcomboboxitemsource

populate static items into c# WPF combo box


I am trying to add the static values in to my combo box which is being written in WPF c#. I have following xaml piece of code which adds the items into my combo box.

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="115200">Item1</ComboBoxItem>
<ComboBoxItem  Name="57600">Item2</ComboBoxItem>
<ComboBoxItem  Name="38400">Item3</ComboBoxItem>
</ComboBox>

But is there any way that I can use "ItemSource" property of the combo box in to my xaml code to populate the combo box or any other UI method to add the static values into combo box. Note: I do not want to do it in coding way to populate the values. I would like find the way of xaml or UI addition only.


Solution

  • You can bind your Combo box items from your view model using item source.

    See the example below:

    First, you want to set the DataContext of your Window.

    /// <summary> 
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel();
        }
    }
    

    Next,

    public class ViewModel
    {
        public ObservableCollection<string> CmbContent { get; private set; }
    
        public ViewModel()
        {
            CmbContent = new ObservableCollection<string>
            {
                "Item 1", 
                "Item 2",
                "Item 2"
    
            };
        }
    }
    

    Finally,

    <Grid>
        <ComboBox Width="200"
              VerticalAlignment="Center"
              HorizontalAlignment="Center"
              x:Name="MyCombo"
              ItemsSource="{Binding CmbContent}" />
    </Grid>