wpf 如何从 xaml 中该行内的模板化单元绑定到 DataGridRow 项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13201286/
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
How to bind to DataGridRow item from templated cell within that row in xaml?
提问by hashlock
What binding is used to bind an element defined in the cell template of a DataGridTemplateColumn to the bound data item of that cell's DataGridRow?
使用什么绑定将 DataGridTemplateColumn 的单元格模板中定义的元素绑定到该单元格的 DataGridRow 的绑定数据项?
For example, assume the DataGrid Items are objects that have a Name property. What binding is required in the code below to bind the TextBlock Text to the "Name" property of the data item represented by the parent row?
例如,假设 DataGrid Items 是具有 Name 属性的对象。下面的代码中需要什么绑定才能将 TextBlock Text 绑定到父行表示的数据项的“Name”属性?
(And yes, in the example I could just use DataGridTextColumn, but I'm just simplifying for example sake.)
(是的,在这个例子中我可以只使用 DataGridTextColumn,但我只是为了简化。)
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ???}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
采纳答案by Peter Hansen
You don't need any special kind of binding - the TextBlock inherits the datacontext from the row (which is set to the bound item).
您不需要任何特殊类型的绑定 - TextBlock 从行(设置为绑定项目)继承数据上下文。
So you can just do this:
所以你可以这样做:
<TextBlock Text="{Binding Name}" />
To see that the datacontext is actually inherited by the TextBlock, you can set a different datacontext which is closer to the TextBlock in the control hierarchy. The TextBlock will now use that datacontext instead.
要查看数据上下文实际上是由 TextBlock 继承的,您可以设置一个不同的数据上下文,该数据上下文更接近控件层次结构中的 TextBlock。TextBlock 现在将改用该数据上下文。
In this example the name of the StackPanel will be shown in the TextBlock instead of the name on the bound row object on the DataGrid:
在此示例中,StackPanel 的名称将显示在 TextBlock 中,而不是 DataGrid 上绑定行对象上的名称:
<DataTemplate>
<StackPanel x:Name="panel1" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<!-- Binds to Name on the Stackpanel -->
<TextBlock Text="{Binding Name}" />
<!-- Binds to Name on object bound to DataGridRow -->
<TextBlock Text="{Binding DataContext.Name,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRow}}" />
</StackPanel>
</DataTemplate>

