绑定DataGridTemplateColumn [英] Binding DataGridTemplateColumn

查看:78
本文介绍了绑定DataGridTemplateColumn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎我碰壁了,试图在DataGrid上使用DataTemplates。我正在尝试使用一个模板为每个单元格显示两行文本。但是似乎无法以任何方式绑定该列。

Seems I've hit a wall trying to use DataTemplates on my DataGrid. What I'm trying to do is to use one template to show two rows of text for each cell. But it doesn't seem to be possible to Bind the column in any way.

下面的代码有望显示我想做的事情。注意每列的Binding:模板列没有这样的东西,因此,这个xaml可能行不通。

Following code hopefully shows what I wish to do. Note the Binding for each column: there is no such thing for a template column, and as such, this xaml couldn't possibly work.

<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复制到每一列只是为了每个副本上的绑定不同?当然有解决这个问题的好方法吗?还是我只是再次错过了令人眼花obvious乱的东西?

Am I doomed to copy the whole DataTemplate to every column just to have a different binding on each copy? Surely there a nice way to go around this? Or am I just missing something blindingly obvious again?

推荐答案

我不确定您要做什么,但是如果您需要获取整行的DataContext, ,您可以使用 RelativeSource 绑定沿可视树移动。像这样:

I'm not completely sure what you're trying to do but if you need to get the DataContext of the whole row, you can use a RelativeSource binding to walk up the visual tree. Like so:

<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>

这篇关于绑定DataGridTemplateColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆