Search code examples
c#.netwpfxamlexpression-blend

Change the Label's foreground colour on MouseOver WPF


I have the following problem: I have a Button, which has a StackPanel inside it, with a ContentControl and a Label within the StackPanel, and I've set the button's properties IsMouseOver and IsPressed to change the button's colour when the action happen. But, I would like to invert the label's colour when the mouse is over the button.

This is my button's code: (because I think my description is not clear enough):

<Button Template="{StaticResource OnMouseOver}" ToolTip="Release" >
    <StackPanel Orientation="Horizontal">
        <ContentControl Template="{StaticResource Release}"/>
        <Label Content="Release" Foreground="#457345" />
    </StackPanel>
</Button>

This is how I changed the button's properties when the button is pressed and when the mouse is over the button:

<ControlTemplate TargetType="Button" x:Key="OnMouseOver">
    <Border x:Name="border" Background="Transparent">
        <ContentPresenter ContentSource="Content" />
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="border" Property="Background" Value="#A1CCA1"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter TargetName="border" Property="Background" Value="#AFD8AF"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

For the record, I've tried to do something like ControlTemplate for my label, but it didn't work, and my label just vanished when I did.

Could you help me?


Solution

  • try this :

        <ControlTemplate TargetType="Button" x:Key="OnMouseOver">
    <Border x:Name="border" Background="Transparent">       
        <StackPanel Orientation="Horizontal">
                <ContentControl />
                <Label x:Name="label" Content="Release" Foreground="#457345" />
            </StackPanel>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="border" Property="Background" Value="#A1CCA1"/> 
             <Setter TargetName="label" Property="Foreground" Value="#AFD8AF"/>     
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter TargetName="border" Property="Background" Value="#AFD8AF"/>
             <Setter TargetName="label" Property="Foreground" Value="#A1CCA1"/> 
        </Trigger>
    </ControlTemplate.Triggers>
    

    <Button x:Name="button" Template="{StaticResource OnMouseOver}" ToolTip="Release" Height="42" VerticalAlignment="Bottom" Margin="235,0,127,143" >
    
        </Button>