[英]Bind DataGridColumns Header to DataContext of the window
I have a DataGrid
and want to bind the Header
-property to a property of my windows DataContext
but I did not get it working.我有一个DataGrid
并且想将Header
属性绑定到我的 windows DataContext
一个属性,但我没有让它工作。
Binding can be such a pain as (for me) it is never clear which context this
has when simply using Binding
.绑定可以是这样的痛苦(对我来说)这是从来没有明确这方面this
只需使用时具有Binding
。 I know that the "Context" in the Binding={}
is a single element of the DataGrid
s ItemsSource
.我知道Binding={}
中的“Context”是DataGrid
的ItemsSource
的单个元素。 But what is the "Context" for Header={Binding ???}
?但是Header={Binding ???}
的“上下文”是什么?
I've already tried:我已经试过了:
Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource Self}}
Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource TemplatedParent}}
Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyWindow}}}
Header="{Binding Path=DataContext.MyProperty, ElementName=MyWindowName}
I tried with and without Path but nothing is working.我尝试使用和不使用 Path 但没有任何效果。
For example, using the last one with ElementName
I get the following binding-exception:例如,将最后一个与ElementName
一起使用,我得到以下绑定异常:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DataContext.MyProperty; DataItem=null; target element is 'DataGridTextColumn' (HashCode=51072575); target property is 'Header' (type 'Object')
Is there any tool to check/change bindings at runtime?是否有任何工具可以在运行时检查/更改绑定? Or even to know what the current "Context" is?或者甚至想知道当前的“上下文”是什么?
Note: The DataGrid
is inside a Mahapps.Flyout (not sure if this has something to say).注意: DataGrid
位于 Mahapps.Flyout 中(不确定这是否有话要说)。
Since DataGridTextColumn
or any other supported data grid columns are not part of visual tree of datagrid
so they don't inherit the DataContext
of datagrid
.由于DataGridTextColumn
或任何其他受支持的数据网格列不是datagrid
可视化树的一部分,因此它们不继承datagrid
的DataContext
。 Since, they don't lie in visual tree so any try to get DataContext
using RelativeSource
won't work.因为,它们不在可视化树中,因此任何使用RelativeSource
获取DataContext
尝试都不起作用。
Solution - You can create a proxy element to bind the data context of window/control
;解决方案——可以创建一个代理元素来绑定window/control
的数据上下文; use that proxy element to bind the Header of DataGridTextColumn
.使用该代理元素绑定DataGridTextColumn
的 Header 。
<Grid>
<Grid.Resources>
<FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
</Grid.Resources>
<ContentControl Visibility="Collapsed" Content="{StaticResource ProxyElement}"></ContentControl>
<DataGrid
ItemsSource="{Binding Collection}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="{Binding DataContext.MyProperty, Source={StaticResource ProxyElement}}" Binding="{Binding PropertyName}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.