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

标签 c# wpf triggers readonly attached-properties

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

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 个错误:

Cannot find the Style Property 'Something' on the type 'ReadonlyAttachedProperty.AttachedPropertyHelper'. Line 11 Position 16.

Property 'Something' was not found in type 'TextBlock'.

最佳答案

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

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

关于c# - 触发器中的只读附加属性 (WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10648997/

相关文章:

mysql - 在表更新时运行 SQL 触发器以设置不同表上的值

wpf - Dispatcher 和 SynchronizationContext 类

c# - NHibernate 对象中对象的刷新()

c# - 如果 SQL DB 列为 NULL 插入到 datagridview 0

c# - 如何在 C# 中重写枚举上的 ToString()?

wpf - 我想从 c# 代码更新 SSRS 报告的共享数据源

Mysql触发器约束检查

sql - ORACLE 更新后触发 : solving ORA-04091 mutating table error

c# - 如何读取特定行的文件

c# - 检查字符串是否可以解析为 int 数组的最佳方法是什么?