[英]Cannot bind an Observable Collection to an Attached Property on an UserControl
我想將自定義類型(BoundItem)的ObservableCollection綁定到視圖。
我這樣使用它:
<v:MyUserControlBase x:Class="My.Views.MyView"
(...)
h:FrameworkElementDropBehavior.MyItems="{Binding Attachments}">
附件在ViewModel中定義為:
public ObservableCollection<BoundItem> Attachments
{
get { return _Attachments; }
set { _Attachments = value; }
}
我的視圖是一個實際的DependencyObject,因為當我在視圖后面的代碼中執行以下代碼時:
MessageBox.Show((this as DependencyObject).ToString());
它顯示“真實”。
我這樣定義了我的Dependency Property:
public static readonly DependencyProperty MyItemsProperty = DependencyProperty.RegisterAttached("MyItems", typeof(ObservableCollection<BoundItem>), typeof(MyView), new FrameworkPropertyMetadata(null));
public static string GetMyItems(DependencyObject element)
{
if (element == null) throw new ArgumentNullException("MyItems");
return (ObservableCollection<BoundItem>)element.GetValue(MyItemsProperty);
}
public static void SetMyItems(DependencyObject element, ObservableCollection<BoundItem> value)
{
if (element == null) throw new ArgumentNullException("MyItems");
element.SetValue(MyItemsProperty, value);
}
發生的錯誤是:
無法在“MyView”類型的“SetMyItems”屬性上設置“綁定”。 '綁定'只能在DependencyObject的DependencyProperty上設置。
謝謝你的幫助:) .x
問題在於您的財產注冊。 而不是所有者類型MyView
它應該是FrameworkElementDropBehavior
i,即您定義屬性的類。
public static readonly DependencyProperty MyItemsProperty =
DependencyProperty.RegisterAttached("MyItems",
typeof(ObservableCollection<BoundItem>),
typeof(FrameworkElementDropBehavior),
new FrameworkPropertyMetadata(null));
此外,SetMyItems第二個參數應為ObservableCollection類型,GetMyItems應具有返回類型ObservableCollection。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.