问题
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.
Binding can be such a pain as (for me) it is never clear which context this has when simply using Binding.
I know that the "Context" in the Binding={} is a single element of the DataGrids ItemsSource. But what is the "Context" for 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.
For example, using the last one with ElementName I get the following binding-exception:
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).
回答1:
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. Since, they don't lie in visual tree so any try to get DataContext using RelativeSource won't work.
Solution - You can create a proxy element to bind the data context of window/control; use that proxy element to bind the Header of DataGridTextColumn.
<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>
来源:https://stackoverflow.com/questions/34067554/bind-datagridcolumns-header-to-datacontext-of-the-window