Bind DataGridColumns Header to DataContext of the window

后端 未结 1 869
[愿得一人]
[愿得一人] 2021-01-23 12:31

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

相关标签:
1条回答
  • 2021-01-23 13:21

    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>
    
    0 讨论(0)
提交回复
热议问题