[英]Binding to attached behaviours
我創建了一個自定義附加行為:
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的值。 這可能嗎?
問題出在您的注冊碼中。 您應該將typeof(CustomItemsBehaviour)
傳遞為所有者類型:
public static readonly DependencyProperty MyTestProperty =
DependencyProperty.RegisterAttached(
"MyTest",
typeof(string),
typeof(CustomItemsBehaviour),
new UIPropertyMetadata(""));
我不確定您要達到的目標,但是我認為附加財產聲明中存在一些錯誤。 嘗試這個 :
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.