简体   繁体   English

将 WPF Datagrid 列设置为 Combobox itemsource

[英]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.我有一个 Combobox,我希望它的项目是位于 DataGrid 上的列数据。 Is there anyway to set the Combobox itemsource to be a specific column of a DataGrid?无论如何将 Combobox itemsource 设置为 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.现在我正在迭代 DataGrid 的每一行,获取字段的数据并将它们添加到 Combobox,但这意味着我必须清除所有项目并在每次修改 DataGrid 时重复。

You can set ItemsSource and DisplayMemberPath properties:您可以设置 ItemsSource 和 DisplayMemberPath 属性:

        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.您的数据网格必须绑定到 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.我想您可以通过提取所需的字段(例如使用 linQ)来构建另一个集合,并将这个新集合公开给您的视图,以便您可以绑定 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.如果您想保持第二个集合的更新,请将您的第一个主集合设为 ObservableCollection,这样您就可以订阅 CollectionChanged 事件。 In the event handler, just manage the add and remove in your combobox source collection.在事件处理程序中,只需管理 combobox 源集合中的添加和删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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