wpf 绑定 DataGridTemplateColumn
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17470738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding DataGridTemplateColumn
提问by ari k
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.
似乎我在尝试在我的 DataGrid 上使用 DataTemplates 时碰壁了。我想要做的是使用一个模板为每个单元格显示两行文本。但似乎不可能以任何方式绑定列。
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.
以下代码有望显示我想要做的事情。注意每一列的绑定:模板列没有这样的东西,因此,这个 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; }
}
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?
我是否注定要将整个 DataTemplate 复制到每一列,只是为了在每个副本上有不同的绑定?当然有一个很好的方法来解决这个问题吗?或者我只是又错过了一些非常明显的东西?
回答by ChrisO
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 RelativeSourcebinding to walk up the visual tree. Like so:
我不完全确定您要做什么,但是如果您需要获取整行的 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>

