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 solution from Johan Larsson works perfectly, only the FallbackValue from the Binding isn't forwarded, so I've changed it like this:
So it could be used like this, here for example for Binding to a Header:
I wrote a markupextension for it:
It enables binding to the DataContext of the current root objet {Window, UserControl, ...}
Sample usage (Visible & Visibility are properties in the viewmodel):
The columns of a
DataGrid
are abstract objects not appearing in the visual or logical tree. You cannot useElementName
andRelativeSource
.Source
in combination withx:Reference
should work though: