Search code examples
wpfxamltilemahapps.metro

How to change tile background on mouse over in WPF?


Using the code provided in this post:

lighten background color on button click per binding with converter

I have written the following code to change the background of a MahApps Tile on MouseOver:

<local:ColorLightConverter x:Key="colorLightConverter" />
    <Style x:Key="aaa" TargetType="mah:Tile">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="{Binding Path=Background.Color, RelativeSource={RelativeSource TemplatedParent}, Mode=OneTime, Converter={StaticResource colorLightConverter}}" />
            </Trigger>
        </Style.Triggers>
    </Style>

The color light converter is the same as written in the post mentioned and the style is used on the Mahapps Metro Tile. The code does not work, because the tile flickers on MouseOver. Also, placing a breakpoint inside the converter, I saw that it is not reached.

What am I doing wrong?


Solution

  • I could reproduce the problem with the Tile control. It never enters the Converter code because TemplatedParent is null. When I changed the RelativeSource to AncestorType={x:Type StackPanel} as it was in my case, the flickering went away and the breakpoint in the converter was reached. You can check if this is the case with you by adding to the Binding FallbackValue=Red in which case the color on mouse over will be Red for a faulty binding.

    Here is my working XAML:

    <Window.Resources>
            <local:ColorLightConverter x:Key="colorLightConverter" />
            <Style x:Key="aaa" TargetType="{x:Type Control}">
                <Setter Property="Background" Value="White"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="{Binding Path=Background.Color, RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Converter={StaticResource colorLightConverter},FallbackValue=Red}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <StackPanel Background="DarkGoldenrod">
            <mah:Tile Title="Hello!" Style="{StaticResource aaa}" 
                        TiltFactor="2"
                        Width="100" Height="100" 
                        Count="1" x:Name="tile">
            </mah:Tile>
            <TextBox Width="100" Height="100" Style="{StaticResource aaa}">Test</TextBox>
        </StackPanel>