I'm trying to bind column visibility to that of another element like this:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>
<StackPanel>
<CheckBox x:Name="chkColumnVisible" Content="Show column" />
<DataGrid x:Name="MyDataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Visibility="{Binding ElementName=chkColumnVisible, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
but I get this error in VS output:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=IsChecked; DataItem=null; target element is 'DataGridTextColumn' (HashCode=48860040); target property is 'Visibility' (type 'Visibility')
Is there a pure XAML way to accomplish this?
The columns of a DataGrid
are abstract objects not appearing in the visual or logical tree. You cannot use ElementName
and RelativeSource
. Source
in combination with x:Reference
should work though:
Visibility="{Binding Source={x:Reference chkColumnVisible},
Path=IsChecked,
Converter={StaticResource BooleanToVisibilityConverter}}"