2013-06-27 34 views
2

我創建了一個自定義的附加行爲:與附着行爲

public static class CustomItemsBehaviour 
{ 
    public static readonly DependencyProperty MyTestProperty = 
    DependencyProperty.RegisterAttached(
     "MyTest", 
     typeof(string), 
     typeof(ItemsControl), 
     new UIPropertyMetadata("")); 

    public static string GetMyTest(ItemsControl itemsControl) 
    { 
     return (string)itemsControl.GetValue(MyTestProperty); 
    } 

    public static void SetMyTest(ItemsControl itemsControl, string value) 
    { 
     itemsControl.SetValue(MyTestProperty, value); 
    } 
} 


我想使用它,像這樣:

<ListBox 
    ItemsSource="{Binding Path=Items}" 
    AttachedBehaviours:CustomItemsBehaviour.MyTest="{Binding TestValue}"> 


但它失敗:

{"A 'Binding' cannot be set on the 'SetMyTest' property of type 'ListBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject."} 


我想將我的視圖模型中的某些值綁定到MyTest的值。這可能嗎?

回答

5

問題在於您的註冊碼。你應該通過typeof(CustomItemsBehaviour)作爲所有者類型:

public static readonly DependencyProperty MyTestProperty = 
DependencyProperty.RegisterAttached(
    "MyTest", 
    typeof(string), 
    typeof(CustomItemsBehaviour), 
    new UIPropertyMetadata("")); 
+0

精氨酸。不知道我是如何錯過的。它現在有效。 – Flack

1

我不知道你想什麼acheive,但我認爲這是在你的附加屬性的聲明,一些錯誤。試試這個:

public static class CustomItemsBehaviour 
{ 
public static readonly DependencyProperty MyTestProperty = 
DependencyProperty.RegisterAttached(
    "MyTest", 
    typeof(string), 
    typeof(CustomItemsBehaviour), 
    new UIPropertyMetadata("")); 

public static string GetMyTest(DependencyObject itemsControl) 
{ 
    return (string)itemsControl.GetValue(MyTestProperty); 
} 

public static void SetMyTest(DependencyObject itemsControl, string value) 
{ 
    itemsControl.SetValue(MyTestProperty, value); 
} 

}

看到這裏DependencyProperty.RegisterAttached