Search code examples
wpfxamltriggersuielement

WPF Style Trigger on Foreign UIElement


If I have 2 Buttons, A and B, is it possible to create a Style and a Trigger such that when the user hovers over Button B, it will cause Button A's Style to change? I've tried using SourceName and TargetName, and am getting compiler errors. Here's the XAML that I'm fooling around with - I'd like to cause Button A's content to be bolded when Button B is moused over:

<Window x:Class="WpfApplication1.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window4" Height="300" Width="300">

<Window.Resources>
    <Style x:Key="BoldWhenOver" TargetType="{x:Type Button}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="FontWeight" Value="Bold" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<StackPanel>
    <Button Name="btnA" Content="A" Style="{StaticResource BoldWhenOver}" />
    <Button Name="btnB" Content="B" />
</StackPanel>


Solution

  • Triggers, by their nature, are used to change properties on the element the trigger is applied to, not other unrelated elements. There are probably some hacks you could implement to make something like this happen, but I don't think it would be good practice or fit with what WPF is meant to do.

    You could embed btnA and btnB into a single user-control (and then have access to both in the UserControl.Triggers), but that might not make logical sense for what you are trying to do. That makes the assumption that btnA and btnB always belong together. If that is not the case, you should just wire this up the old-fashioned way, with a couple events and some code-behind:

    <StackPanel>
       <Button Name="btnA" Content="A"/>
       <Button Name="btnB" Content="B" MouseEnter="btnB_MouseEnter" MouseLeave="btnB_MouseLeave"/>
    </StackPanel>
    

    And the code:

    private void btnB_MouseEnter(object sender, MouseEventArgs e)
    {
        btnA.FontWeight = FontWeights.Bold;
    }
    
    private void btnB_MouseLeave(object sender, MouseEventArgs e)
    {
        btnA.FontWeight = FontWeights.Normal;
    }