2012-05-18 34 views
4

我遇到只讀附加屬性的問題。 我這樣定義它:觸發器中的只讀附屬屬性(WPF)

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」。 Line 11 Position 16.

Property'Something'在'TextBlock'類型中找不到。

回答

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

是的,我知道。但我對這種方式感興趣... – Developex

+1

在哪種方式?你想實現什麼? – LPL

+0

我想使用READ-ONLY附加屬性。 – Developex