Home > Enterprise >  Hide a control with trigger on another
Hide a control with trigger on another

Time:10-01

I have a <TextBlock x:Key="_tb1"/> and another <TextBlock x:Key="_tb2"/>.

How to set visibility of _tb1 when for exemple IsMouseOver of _tb2 is true ?

CodePudding user response:

x:Key is allowed for resources and dictionary elements only! Code won't compile/run when x:Key is declared in <TextBloxk/>.

This is an example of what you want to implement..

In xaml

<TextBlock Text="AA"
           x:Name="AA"
           MouseEnter="AA_OnMouseEnter"
           MouseLeave="AA_OnMouseLeave"/>

<TextBlock Text="BB"
           x:Name="BB"/>

In code behind

private void AA_OnMouseEnter(object sender, MouseEventArgs e)
{
    BB.Visibility = Visibility.Hidden;
}

private void AA_OnMouseLeave(object sender, MouseEventArgs e)
{
    BB.Visibility = Visibility.Visible;
}

CodePudding user response:

As @MuhammadSulaiman correctly wrote, x:Key is used only in resources and will not work in layout.
You must specify x:Name in the layout.
And then this XAML will work:

<StackPanel>
    <TextBlock x:Name="tb1" Text="Some Text" Background="Transparent"/>
    <TextBlock x:Name="tb2" Text="Popup text" Background="LightYellow">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="Visibility" Value="Collapsed"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=tb1}"
                                    Value="True">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</StackPanel>
  • Related