在WPF中的UserControl中显示/隐藏DataTemplate中的控件

时间:2011-09-15 11:02:41

标签: wpf xaml data-binding

我有一个UserControl,有一个带DataTemplate的ListView控件,在DataTemplate中我定义了一个CheckBox,它将根据UserControl的一个名为ShowCheckBox的属性显示。

如何获取UserControl的引用,以便我可以执行以下操作:

<UserControl x:Class="WpfApplication15.UserControl2"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <ListView>
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="500">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Visibility="{Binding ??? this.ShowCheckBox ??? }" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</UserControl>

2 个答案:

答案 0 :(得分:3)

您可以使用BooleanToVisibilityConverterRelativeSourceBinding

<UserControl x:Class="WpfApplication15.UserControl2"
             ...>
    <UserControl.Resources>
       <BooleanToVisibilityConverter x:Key="Converter" />
    </UserControl.Resources>
    <ListView>
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="500">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Visibility="{Binding 
                                      RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, 
                                      Path=ShowCheckBox, 
                                      Converter={StaticResource Converter}}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</UserControl>

答案 1 :(得分:1)

调用您的UserControl,x:Name="This"
而不是:

    <Visibility={Binding ElementName=This, Path=MyProperty}>

假设您的属性属于Visibility类型(如果它是bool,您应该按照另一个答案的建议使用BoolToVisibilityConverter)