绑定DataGridTemplateColumn

时间:2013-07-04 12:47:20

标签: 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; }
}

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

1 个答案:

答案 0 :(得分:4)

我不完全确定你要做什么,但如果你需要获取整行的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>