WPF:如何绑定DataGrid的单个单元格

问题描述:

提前感谢您的帮助。  我是WPF的新手,我从以下示例开始:

Thank you in advance for your help.  I am a newbie to WPF, and I followed the example from:

https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/data -templating-overview#styling-and-templating-an-itemscontrol

https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview#styling-and-templating-an-itemscontrol

这个优秀的例子向我们展示了如何使用ItemTemplateSelector for ListBox。  (对于我到目前为止发现的所有其他示例,数据对象被限制在ListBox中的一行。  DataGrid相同 - 绑定仅适用于行: 每个
属性data object 是DataGrid的一列。)

This excellent example showed us how to use ItemTemplateSelector for ListBox.  (And with all other examples I found so far, the data object is bounded to one row in the ListBox.  The same for DataGrid - binding is for row only:  each of the properties in the data object  is a column of the DataGrid.)

在我的例子中,我需要将数据对象绑定到DataGrid中的每个单元格。  例如,yy DataGrid有10列10行。  我的数据结构不是列表,但是是10x10项目的矩阵(我们称之为Task),
中的每个单元格DataGrid都是一个Task对象。 

In my case, I need to bind a data object to each of the cell in the DataGrid.  For example, yy DataGrid has 10 columns and 10 rows.  My data structure is not a list, but is is a matrix of 10x10 item (let's call it Task), and each of the cell in the DataGrid is a Task object. 

是否可以将数据对象绑定到WPF中的DataGird中的单元格?  如果是这样,请指点我正确的方向?  任何指示或示例都将不胜感激。

Is is possible to bin a data object to a cell in DataGird in WPF?  If so, could you please point me the the right direction?  Any instruction or example would be greatly appreciated.

再次,非常感谢您的时间和考虑。

Again, thank you so much for time and consideration.

祝你好运,

数据网格虽然是ItemsControl但不像listbox。

A datagrid while it is an ItemsControl does not template like a listbox.

数据网格需要一组对象,然后数据网格的每个单元格都绑定到列表中对象的特定属性。

The datagrid wants a collection of objects and each cell of the datagrid is then bound to a particular property in the object in the list.

<DataGrid Name="_dataGrid" ItemsSource="{Binding yourList}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Column 1" Binding="{Binding [0]}"/>
        <DataGridTextColumn Header="Column 2" Binding="{Binding [1]}"/>
    </DataGrid.Columns>
</DataGrid>

如果您将阵列更改为列表,那么这将有效。  但是既然你说每个项目都是一个任务(我假设它是一个具有多个属性的对象),这可能不起作用,因为DataGrid中的每个项目通常都绑定到一个属性。

If you change your array to a list then this will work.  But since you said each item is a Task (I assume it is an object with multiple properties) this might not work since each items in the DataGrid is usually bound to a single property.