wpfbindingdependency-propertiesattached-properties

WPF does not seem to find a custom attached property


I am trying to bind a property (Button.Background) to a property on my custom attached property.

In a C# file I have

public static class Square
{
    public static readonly DependencyProperty PlayerProperty =
        DependencyProperty.RegisterAttached
        (
            name           : "Player",
            propertyType   : typeof(Player),
            ownerType      : typeof(UIElement),
            defaultMetadata: new FrameworkPropertyMetadata(null)
        );

    public static Player GetPlayer(UIElement element)
    {
        return (Player)element.GetValue(PlayerProperty);
    }

    public static void SetPlayer(UIElement element, Player player)
    {
        element.SetValue(PlayerProperty, player);
    }

    // Other attached properties
}

A snippet of my XAML is

<Grid Name="board" Grid.Row="1" Grid.Column="1">
    <Grid.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Height" Value="20" />
            <Setter Property="Width" Value="20" />
            <Setter Property="BorderThickness" Value="3" />
            <Setter Property="Background"
                Value="{Binding Path=(l:Square.Player).Brush, Mode=OneWay}" />
        </Style>
    </Grid.Resources>
</Grid>

This is the error I get:

Cannot convert string '(l:Square.Player).Brush' in attribute 'Path' to object of type 'System.Windows.PropertyPath'.

Property path is not valid. 'Square' does not have a public property named 'Player'.

Error at object 'System.Windows.Data.Binding' in markup file 'Gobang.Gui;component/mainwindow.xaml' Line 148 Position 59.

But since Player is an attached property which is on Square, the above code should work, right?


Solution

  • I believe your attached property should designate Square as the owner rather than UIElement.

    public static readonly DependencyProperty PlayerProperty =
        DependencyProperty.RegisterAttached("Player", typeof(Player),
            typeof(Square), new FrameworkPropertyMetadata(null));