Reputation: 4359
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?
Upvotes: 1
Views: 938
Reputation: 4359
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>
Upvotes: 1