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.
Bindi
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>