似乎我在DataGrid上使用DataTemplates遇到了麻烦。我想要做的是使用一个模板为每个单元格显示两行文本。但似乎不可能以任何方式绑定该列。
下面的代码很有希望地展示了我希望做的事情。注意每一列的绑定:模板列没有这样的东西,因此,这个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复制到每一列,只是为了在每个副本上有一个不同的绑定?肯定有一个好的方法来解决这个问题吧?或者我只是又一次错过了一些显而易见的东西?
发布于 2013-07-04 22:55:21
我不完全确定您想要做什么,但是如果您需要获取整行的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>https://stackoverflow.com/questions/17470738
复制相似问题