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 的值。这可能吗?

4

2 回答 2

5

问题出在您的注册码中。typeof(CustomItemsBehaviour)您应该作为所有者类型传递:

public static readonly DependencyProperty MyTestProperty =
 DependencyProperty.RegisterAttached(
     "MyTest",
     typeof(string),
     typeof(CustomItemsBehaviour),
     new UIPropertyMetadata(""));
于 2013-06-27T14:19:48.200 回答
1

我不确定您要达到什么目的,但我认为您的附加财产的声明存在一些错误。尝试这个 :

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

于 2013-06-27T14:24:22.343 回答