Can I use TemplateBinding in a VisualState Setter?

201 Views Asked by At

I'm trying to bind a property value in a VisualState to a property of the templated FrameworkElement using TemplateBinding but it doesn't work. There are no errors but no results, either. Here's an example of what I tried:

public class ButtonEx : Button
{
    public ButtonEx() : base() { }

    public static readonly DependencyProperty BackgroundPointerOverProperty = DependencyProperty.Register(
        "BackgroundPointerOver", typeof(SolidColorBrush), typeof(ButtonEx), new PropertyMetadata(null));
    public SolidColorBrush BackgroundPointerOver
    {
        get => (SolidColorBrush)GetValue(BackgroundPointerOverProperty);
        set => SetValue(BackgroundPointerOverProperty, value);
    }
}

The Control Template:

<ControlTemplate TargetType="classes:ButtonEx">
    <Grid x:Name="LayoutRoot" >

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal" />

                <VisualState x:Name="PointerOver">
                    <VisualState.Setters>
                        <Setter Target="LayoutRoot.Background" Value="{TemplateBinding BackgroundPointerOver}" />
                    </VisualState.Setters>
                </VisualState>

            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

    </Grid>
</ControlTemplate>

Shouldn't the Setter set the ButtonEx background to the value of the parent property on mouse-over? This is in a WinUI 3 Desktop App.

1

There are 1 best solutions below

2
Andrew KeepCoding On

You can make it work binding via RelativeSource.

<VisualState x:Name="PointerOver">
    <VisualState.Setters>
        <Setter Target="LayoutRoot.Background" Value="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=BackgroundPointerOver}" />
    </VisualState.Setters>
</VisualState>