似乎我在尝试在我的数据网格上使用数据模板时遇到了麻烦。我要做的是使用一个模板为每个单元格显示两行文本。但似乎不可能以任何方式绑定列。
下面的代码希望能显示我想要做的事情。注意每个列的绑定:模板列没有这样的东西,因此,这个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; }
}

我是否注定要将整个数据模板复制到每一列,以便在每个副本上具有不同的绑定?有什么好办法可以绕过这个吗?还是我又错过了一些显而易见的东西?

最佳答案

我不完全确定你要做什么,但是如果你需要得到整个行的DATACONTRONT,你可以使用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>

关于c# - 绑定(bind)DataGridTemplateColumn,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17470738/

10-13 06:45
查看更多