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?