Ask Your Question

Revision history [back]

To bind a DataGridComboBoxColumn to an ObservableCollection, you can follow these steps:

  1. Define your Observable Collection:
public ObservableCollection<string> MyCollection { get; set; }
  1. Populate your ObservableCollection in your ViewModel:
MyCollection = new ObservableCollection<string>();
MyCollection.Add("Item1");
MyCollection.Add("Item2");
MyCollection.Add("Item3");
  1. Define your DataGridComboBoxColumn in XAML:
<DataGridComboBoxColumn Header="My Combo Column" 
                        SelectedItemBinding="{Binding SelectedItemProperty}" 
                        ItemsSource="{Binding MyCollection}"
                        DisplayMemberPath="."/>
  1. Add a Property to your ViewModel to hold the selected item from the combo box:
private string _selectedItem;
public string SelectedItemProperty
{
    get { return _selectedItem; }
    set 
    {
        _selectedItem = value;
        OnPropertyChanged(nameof(SelectedItemProperty));
    }
}
  1. Make sure your ViewModel implements INotifyPropertyChanged interface, so that the UI can get notified of any property changes:
public class MyViewModel : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}
  1. Set your ViewModel as the DataContext of your view:
public MainWindow()
{
    InitializeComponent();
    DataContext = new MyViewModel();
}

With these steps, you will be able to bind your DataGridComboBoxColumn to your ObservableCollection.