触发器中的只读附加属性(WPF)

7

我有一个只读的附加属性问题。 我是这样定义它的:

public class AttachedPropertyHelper : DependencyObject
{

    public static readonly DependencyPropertyKey SomethingPropertyKey = DependencyProperty.RegisterAttachedReadOnly("Something", typeof(int), typeof(AttachedPropertyHelper), new PropertyMetadata(0));

    public static readonly DependencyProperty SomethingProperty = SomethingPropertyKey.DependencyProperty;

}

我希望在XAML中使用它:

<Trigger Property="m:AttachedPropertyHelper.Something" Value="0">
                        <Setter Property="FontSize" Value="20"/>
                    </Trigger>

但是编译器不想使用它。

结果出现了2个错误:

在类型 'ReadonlyAttachedProperty.AttachedPropertyHelper' 上找不到样式属性'Something'。行11位置16。

'TextBlock'类型中未找到属性'Something'。

2个回答

6

我不知道你的只读附加属性是否有什么特殊之处,但如果你按照默认方式声明它,它是有效的:

public class AttachedPropertyHelper : DependencyObject
{
    public static int GetSomething(DependencyObject obj)
    {
        return (int)obj.GetValue(SomethingProperty);
    }

    public static void SetSomething(DependencyObject obj, int value)
    {
        obj.SetValue(SomethingProperty, value);
    }

    // Using a DependencyProperty as the backing store for Something. This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SomethingProperty =
        DependencyProperty.RegisterAttached("Something", typeof(int), typeof(AttachedPropertyHelper), new UIPropertyMetadata(0));
}

编辑

如果您想要将相同的内容作为只读附加属性更改,请执行以下操作:

public class AttachedPropertyHelper : DependencyObject
{
    public static int GetSomething(DependencyObject obj)
    {
        return (int)obj.GetValue(SomethingProperty);
    }

    internal static void SetSomething(DependencyObject obj, int value)
    {
       obj.SetValue(SomethingPropertyKey, value);
    }

    private static readonly DependencyPropertyKey SomethingPropertyKey =
        DependencyProperty.RegisterAttachedReadOnly("Something", typeof(int), typeof(AttachedPropertyHelper), new UIPropertyMetadata(0));

    public static readonly DependencyProperty SomethingProperty = SomethingPropertyKey.DependencyProperty;
}

1
以什么方式?你想要实现什么? - LPL
抱歉我的反应有点慢。你仍需要为CLR包装器添加一个公共的get访问器,然后它就可以工作了。 - LPL

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接