简体   繁体   中英

Set WPF Datagrid column as a Combobox itemsource

I have a Combobox, in which I would like its items to be the column data that is located on a DataGrid. Is there anyway to set the Combobox itemsource to be a specific column of a DataGrid?

Right now I'm iterating each row of the DataGrid, getting the field's data and adding them to the Combobox, but that means that I would have to clear all the items and reiterate everytime the DataGrid is modified.

You can set ItemsSource and DisplayMemberPath properties:

        comboBox1.ItemsSource = dataGrid1.ItemsSource;
        comboBox1.DisplayMemberPath = "ColumnName";

I Think you'are taking the wrong approach. Your data grid must be bound to a collection of object. I guess you could just build another collection by extracting the desired fields (for example with linQ) and expose this new collection to your view such that you can bind your combobox.

I you want to keep this second collection updated, make your first main collection an ObservableCollection such taht your can subscribe to CollectionChanged Event. In the event handler, just manage the add and remove in your combobox source collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM