开发者

How to change ItemsSource of ComboBox inside DataGrid?

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 开发者_StackOverflow社区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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜