绑定DataGridTemplateColumn

ari*_*i k 12 c# wpf datagrid datatemplate datagridtemplatecolumn

似乎我试图在我的DataGrid上使用DataTemplates.我要做的是使用一个模板为每个单元格显示两行文本.但似乎不可能以任何方式绑定列.

以下代码希望显示我想做的事情.请注意每列的Binding:模板列没有这样的东西,因此,这个xaml可能无法工作.

<Window.Resources>
    <DataTemplate x:Key="DoubleField">
        <StackPanel>
            <TextBlock Text="{Binding Value1}"/>
            <TextBlock Text="{Binding Value2}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Title}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Price}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Stuff}"/> // <- Binding does not exist for templatecolumn, I only wish it did
    </DataGrid.Columns>
</DataGrid>

class MyListItem {
    class DoubleItem {
        string Value1 { get; set; }
        string Value2 { get; set; }
    }    
    DoubleItem Title { get; set; }
    DoubleItem Price { get; set; }
    DoubleItem Stuff { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我注定要将整个DataTemplate复制到每一列只是为了在每个副本上有不同的绑定吗?当然有一个很好的方式来解决这个问题?或者我只是错过了一些令人眼花缭乱的明显事物?

Chr*_*isO 3

我不完全确定您要做什么,但如果您需要获取整行的 DataContext,您可以使用绑定RelativeSource来遍历可视化树。就像这样:

<DataTemplate x:Key="DoubleField">
    <StackPanel>
        <TextBlock Text="{Binding DataContext.Value1, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
        <TextBlock Text="{Binding DataContext.Value2, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
    </StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)