【问题标题】:Read-only attached property in trigger (WPF)触发器中的只读附加属性 (WPF)
【发布时间】:2012-05-18 08:07:31
【问题描述】:

我对只读附加属性有疑问。 我是这样定义的:

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”中找不到属性“某物”。

【问题讨论】:

    标签: c# wpf triggers readonly attached-properties


    【解决方案1】:

    我不知道你的只读附加属性是否有什么特别之处,但如果你以默认方式声明它,它就可以工作:

    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;
    }
    

    【讨论】:

    • 以哪种方式?你想达到什么目标?
    • 对不起我的迟钝。您仍然需要 CLR 包装器的公共 get 访问器。然后它会工作。
    猜你喜欢
    • 2018-03-15
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多