似乎我已经打了个墙,试图在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复制到每个列,只是对每个副本都有不同的约束?当然有一个很好的方法来解决这个问题吗?或者我只是再次错过了一些明显的事情?
解决方法
我不完全确定你想要做什么,但如果您需要获取整行的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>