我有这样一个用户控件:
<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>
显示地址声明:
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的dependency属性在listview中隐藏或显示datagrid的某些列。通过这种方式,我可以直接从包含usercontrol的窗口控制显示哪些列。这可能吗?
我尝试使用以下代码时,在输出控制台上出现错误:
{Binding Path=ShowAddress, Converter={StaticResource BoolToVisible}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}
系统窗户。数据错误:4:找不到引用“RelativeSource FindAncestor,AncestorType=”System的绑定源。窗户。控制。UserControl',AncestorLevel='1'。BindingExpression:Path=ShowAddress;DataItem=null;目标元素是“DataGridTextColumn”(HashCode=55248170);目标属性为“可见性”(类型为“可见性”)
也许可以使用资源usercontrol来完成,但是datagrid对usercontrol中定义的资源没有作用域。
注意:布尔图可见是一个转换器,将“真”转换为“可见”,将“假”转换为“崩溃”。
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>
霍普,这有帮助