我遇到只读附加属性的问题。 我用这种方式定义了它:
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'。
答案 0 :(得分:4)
我不知道您的只读附加属性是否有特殊内容,但如果您以默认方式声明它,则可以正常工作:
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;
}