我有这样的用户控件:
<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声明:
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为null,我将ListView ItemsSource设置为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; }
}
我需要UserControl的依赖项属性隐藏或在listview中显示datagrid的某些列。这样我可以直接从包含usercontrol的窗口控制哪些列显示。这可能吗?
我尝试使用以下代码,输出控制台出错:
{Binding Path=ShowAddress, Converter={StaticResource BoolToVisible}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}
System.Windows.Data错误:4:找不到绑定源 参考'RelativeSource FindAncestor, AncestorType = 'System.Windows.Controls.UserControl', AncestorLevel = '1'”。 BindingExpression:路径= ShowAddress;的DataItem = NULL; target元素是'DataGridTextColumn'(HashCode = 55248170);目标 属性是“可见性”(类型“可见性”)
也许可以使用资源usercontrol完成,但datagrid没有用户控件中定义的资源的范围。
注意:BoolToVisible是一个将“true”转换为“Visible”和“false”转换为“Collapsed”的转换器。
答案 0 :(得分:1)
RelativeSource扩展程序不适用于DataGridTextColumn(或任何其他DataGridColumn),因为此列不是逻辑树的一部分。您可以执行一些变通方法操作,例如:
<UserControl x:Class="Test31990722.Contacts"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Test31990722"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Name="uc">
<UserControl.Resources>
<local:BoolToVisible x:Key="BoolToVisible" />
</UserControl.Resources>
<ListView Name="lv">
<ListView.ItemTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Contacts}" AutoGenerateColumns="False"
Tag="{Binding ShowAddress, ElementName=uc,Converter={StaticResource BoolToVisible}}">
<DataGrid.Resources>
<TextBlock x:Key="FileNameColHeader" Text="Address" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=Tag}"/>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTextColumn Binding="{Binding Address}" Header="{StaticResource FileNameColHeader}"
Visibility="{Binding Tag, Source={StaticResource FileNameColHeader}}"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
希望,这有帮助