I have a usercontrol like this:
<UserControl>
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<DataGrid ItemSource="{Binding Contacts}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTextColumn Binding="{Binding Address}"
Visibility="{Binding Path=ShowAddress,
Converter={StaticResource BoolToVisible}}"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
ShowAddress declaration:
public bool ShowAddress
{
get { return (bool)GetValue(ShowAddressProperty); }
set { SetValue(ShowAddressProperty, value); }
}
public static readonly DependencyProperty ShowAddressProperty =
DependencyProperty.Register("ShowAddress", typeof(bool), typeof(Contacts), new PropertyMetadata(true));
DataContext is null, i set the ListView ItemsSource as an IEnumerable of Persons
public class Persons
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Persons> Contacts { get; set; }
}
I need a dependency property of the UserControl hide or show certain columns of the datagrid in the listview. This way i can control which columns show, directly from the window that includes the usercontrol. Is this possible?
I trying with the following code, I get an error on the output console:
{Binding Path=ShowAddress, Converter={StaticResource BoolToVisible}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=ShowAddress; DataItem=null; target element is 'DataGridTextColumn' (HashCode=55248170); target property is 'Visibility' (type 'Visibility')
Maybe it can be done with a resource usercontrol, but the datagrid has no scope to the resource defined in the usercontrol.
Note: BoolToVisible is a converter to convert "true" into "Visible" and "false" into "Collapsed".