WPF似乎没有找到自定义附加属性

Jam*_*mie 1 wpf binding dependency-properties attached-properties

我试图将属性(Button.Background)绑定到我的自定义附加属性上的属性.

在我的C#文件中

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
}
Run Code Online (Sandbox Code Playgroud)

我的XAML片段是

<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>
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

无法将属性'Path'中的字符串'(l:Square.Player).Brush'转换为'System.Windows.PropertyPath'类型的对象.

属性路径无效.'Square'没有名为'Player'的公共属性.

标记文件'Gobang.Gui; component/mainwindow.xaml'中对象'System.Windows.Data.Binding'出错'第148行位置59.

但由于Player是附加属性Square,上面的代码应该工作,对吗?

mje*_*nes 5

我相信你附属的财产应该指定Square作为所有者而不是UIElement.

public static readonly DependencyProperty PlayerProperty =
    DependencyProperty.RegisterAttached("Player", typeof(Player),
        typeof(Square), new FrameworkPropertyMetadata(null));
Run Code Online (Sandbox Code Playgroud)