0
votes

I have a WPF DataGrid contained in a UserControl.

In the ViewModel for the user control I have the following defined:

private Visibility _ColumnVisibility;
public Visibility ColumnVisibility
{
get { return _ColumnVisibility;}
set {this._ColumnVisibility= value;
     OnNotifyPropertyChanged("ColumnVisibility");}
}

My Column definition in XAML looks like this:

<DataGrid.Columns>
  <DataGridTextColumn Binding="{Binding UserCode}"
    Header="UserCode"
    Visibility="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=ColumnVisibility}"/>
</DataGrid.Columns>

I get the following exception at runtime:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=ColumnVisibility; DataItem=null; target element is 'DataGridTextColumn' (HashCode=21737301); target property is 'Visibility' (type 'Visibility')

What is the best way (easiest) way to bind DataGrid column visibility to a property defined in the ViewModel of the containing UserControl?

1
Why RelativeSource when you want to bind to a property in the view model of the usercontrol?NtFreX
Dr.Fre: So the correct way to bind would be...?JohnB
Did you try this? Visibility="{Binding Path=DataContext.ColumnVisibility, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>15ee8f99-57ff-4f92-890c-b56153
EP: In my case, wouldn't my ancestor be the UserControl (Since it's within the viewmodel that my property is defined within)JohnB

1 Answers

1
votes

I found an elegant solution in SO by AnjumSKhan here: How to hide wpf datagrid columns depending on a property

<!-- 
AnjumSKhan: I would prefer a more elegant approach which involves using a Freezable.
-->
<Window.Resources>
<DiscreteObjectKeyFrame x:Key="FlagKey" Value="{Binding Flag}"/>
</Window.Resources>