首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绑定DataGridTemplateColumn

绑定DataGridTemplateColumn
EN

Stack Overflow用户
提问于 2013-07-04 20:47:20
回答 1查看 7.5K关注 0票数 14

似乎我在DataGrid上使用DataTemplates遇到了麻烦。我想要做的是使用一个模板为每个单元格显示两行文本。但似乎不可能以任何方式绑定该列。

下面的代码很有希望地展示了我希望做的事情。注意每一列的绑定:模板列没有这样的东西,因此,这个xaml不可能工作。

代码语言:javascript
复制
<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复制到每一列,只是为了在每个副本上有一个不同的绑定?肯定有一个好的方法来解决这个问题吧?或者我只是又一次错过了一些显而易见的东西?

EN

回答 1

Stack Overflow用户

发布于 2013-07-04 22:55:21

我不完全确定您想要做什么,但是如果您需要获取整行的DataContext,您可以使用RelativeSource绑定遍历可视化树。如下所示:

代码语言:javascript
复制
<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>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17470738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档