我创建了一个自定义附加行为:
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的值。这可能吗?
答案 0 :(得分:5)
问题在于您的注册码。您应该将typeof(CustomItemsBehaviour)
作为所有者类型传递:
public static readonly DependencyProperty MyTestProperty =
DependencyProperty.RegisterAttached(
"MyTest",
typeof(string),
typeof(CustomItemsBehaviour),
new UIPropertyMetadata(""));
答案 1 :(得分: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);
}
}