views:

734

answers:

2

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("Player", typeof(Player),
            typeof(UIElement), 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?

Also, when I change my pre tags to code tags, everythin

A: 

You can't set up a binding in the way that you're doing it - you'll need an instance of either Square or Player to bind to that.

Andy
I'm not trying to bind to an instance of Square, Square is where my attached property declaration is.
Jamie
+2  A: 

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));
mjeanes
That's what I get for not reading the intellisense tooltip, sigh. The binding doesn't quite work (the background doesn't change), but that should just be some silly thing I'll look at tomorrow. Thanks a lot, I had wasted so much time on this.
Jamie