【问题标题】:WPF does not seem to find a custom attached propertyWPF 似乎没有找到自定义附加属性
【发布时间】:2024-05-01 04:05:02
【问题描述】:

我正在尝试将一个属性 (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 的 sn-p 是

<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”出错。

但是由于PlayerSquare 上的附加属性,所以上面的代码应该可以工作,对吧?

【问题讨论】:

    标签: wpf binding dependency-properties attached-properties


    【解决方案1】:

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

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

    【讨论】:

    • 这就是我没有阅读智能感知工具提示的结果,叹息。绑定不太有效(背景没有改变),但这应该只是我明天会看的一些愚蠢的事情。非常感谢,我在这上面浪费了很多时间。
    【解决方案2】:

    我让它工作了。 注意:它是一个只读属性,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);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您不能以您正在做的方式设置绑定 - 您需要 SquarePlayer 的实例来绑定。

      【讨论】:

      • 我没有尝试绑定到 Square 的实例,Square 是我附加的属性声明所在的位置。