Ask Your Question
0

How to bind a DataGridComboBoxColumn to an ObservableCollection?

asked 2021-09-03 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-04-15 02:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-03 11:00:00 +0000

Seen: 10 times

Last updated: Apr 15 '22