Bind DataGridColumns Header to DataContext of the window

本秂侑毒 提交于 2020-01-06 04:18:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!