Search code examples
wpfdata-bindingbindingwpfdatagrid

How to bind DataGridTemplateColumn.Visibility to a property outside of DataGrid.ItemsSource?


I need to bind the Visibility of a DataGridTemplateColumn to a property outside of the DataGrid.ItemsSource,because i need to bind this column in the all the rows to one property inside the ViewModel,but as far as i know you just can bind that to something inside the ItemsSource or you should use ElementStyle and EditingElementStyle I've Already tried this code:

 <DataGridTemplateColumn Header="post" 
                      Visibility="{Binding DataContext.ProjectPostVisibility
                    , RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>

And i'm Sure my binding is correct because it works fine when i bind the DataGridCell.Visibility like below:

<DataGridTemplateColumn Header="post">
    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Setter Property="Visibility" Value="{Binding DataContext.ProjectPostVisibility,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn >

Solution

  • Your binding is correct, but it won't work with DataGridTemplateColumn directly because it's not in the visual tree. So it's not inherting DataContext.

    You need to bind the DataGridTemplateColumn from code behind. Here is a demo that shows a way of doing it.