0
votes

Scenario: I have a ContentControl in my View whose Content property is bound with a DataGrid in ViewModel. I will find out the exact number of Columns to display in DataGrid at runtime that's why I am progrmmatically creating DataGrid in ViewModel. My DataGrid's ItemsSource is a DataTable. I am setting DataGrid's 'AutoGeneratingColumns' to False and I am manually creating columns. My DataGrid, along with many other columns, have two ComboBox type columns. I have to change ItemsSource of second ComboBox based on selected index of first ComboBox. So each row of my DataGrid can have different ItemsSource for second ComboBox.

My Question is how can I dynamically change ItemsSource of second ComboBox based on selected index in first ComboBox at runtime in a single row of DataGrid? I also would like to know if there is any better solution possible than my current approach in this scenario?

1
Assuming you have multiple collections in your view model which could be used as Item Source to second combobox, are these collections of common type? If yes then you could create a property like SelectedCollection and set its value depending on selected item of first combo box. And bind your second combo box itemsource to this SelectedCollection property.RockWorld

1 Answers

0
votes

If you working with a viewmodel, it's not that hard. Bind you comboboxes itemssources to properties on your viewmodel. Bind the first combobox's selecteditem to a property on your viewmodel. In the setter of that property, change the collection of the second combobox.

With viewmodels, this is the easiest method. Although creating datagrid columns in you view is not, you could move that to a helper class and call it from the code behind or subclass te datagrid. With runtime columns it's hard, I know.

Update: What I normally do is to use normal columns when showing data, and comboboxes on the row which is selected. That way you won't have that problem You'll have to synchronise the selecteditemproperty when the selecteditem of the datagrid changes. That will also trigger the update of the itemssource of the second combobox

Another option is to make to collections of the combobox subitems in your main collection and pre-populate them. And change the collection of combobox 2 on changes of the selected item in combobox 1. But that could be potentionally be a lot work and storage.