unruledboy
unruledboy

Reputation: 2333

Show/Hide a control in DataTemplate in UserControl in WPF

I have a UserControl, there is a ListView control with DataTemplate, in the DataTemplate I define a CheckBox to be shown based on a property of the UserControl called ShowCheckBox.

How do I get the reference to the UserControl so I can do some thing like:

<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>

Upvotes: 1

Views: 3439

Answers (2)

Ray
Ray

Reputation: 46585

You could to use a BooleanToVisibilityConverter and a RelativeSourceBinding.

<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>

Upvotes: 3

Amittai Shapira
Amittai Shapira

Reputation: 3827

Call your UserControl, this: x:Name="This"
And than:

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

Assuming your property is of type Visibility (if it's bool you should use BoolToVisibilityConverter as suggested in another answer)

Upvotes: 1

Related Questions