似乎我在尝试在我的 DataGrid 上使用 DataTemplates 时遇到了困难。我想要做的是使用一个模板为每个单元格显示两行文本。但是似乎不可能以任何方式绑定(bind)列。
以下代码有望显示我希望做的事情。请注意每一列的绑定(bind):模板列没有这样的东西,因此,这个 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 复制到每一列,只是为了对每个副本进行不同的绑定(bind)?当然有解决这个问题的好方法吗?或者我只是再次遗漏了一些非常明显的东西?
最佳答案
我不完全确定您要做什么,但如果您需要获取整行的 DataContext,您可以使用 RelativeSource
绑定(bind)在可视化树中向上移动。像这样:
<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>
关于c# - 绑定(bind) DataGridTemplateColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17470738/