1

我正在尝试将属性(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
}

我的 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>

这是我得到的错误:

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

属性路径无效。“Square”没有名为“Player”的公共属性。

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

但是既然Player是 on 的附加属性Square,上面的代码应该可以工作,对吧?

4

3 回答 3

5

我相信您的附加属性应该将 Square 指定为所有者,而不是 UIElement。

public static readonly DependencyProperty PlayerProperty =
    DependencyProperty.RegisterAttached("Player", typeof(Player),
        typeof(Square), new FrameworkPropertyMetadata(null));
于 2009-07-22T14:12:53.140 回答
0

我让它工作。注意:它是一个只读属性,Helper 类必须继承自 DependencyObject

public class Helper : DependencyObject
{
    public static readonly DependencyPropertyKey IsExpandedKey = DependencyProperty.RegisterAttachedReadOnly(
        "IsExpanded", typeof(bool), typeof(Helper), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits));

    public static readonly DependencyProperty IsExpandedProperty = IsExpandedKey.DependencyProperty;

    public static bool GetIsExpanded(DependencyObject d)
    {
        return (bool)d.GetValue(IsExpandedKey.DependencyProperty);
    }

    internal static void SetIsExpanded(DependencyObject d, bool value)
    {
        d.SetValue(IsExpandedKey, value);
    }
}
于 2011-01-18T12:25:33.250 回答
-1

你不能以你正在做的方式设置绑定——你需要一个实例Square或者Player绑定到它。

于 2009-07-22T13:58:02.423 回答