2008-12-10 60 views
6

以下XAML(下面)定義資源中的自定義集合,並嘗試用自定義對象填充它;如何解決WPF設計器錯誤'類型{0}不支持直接內容'。'?

<UserControl x:Class="ImageListView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300" 
    xmlns:local="clr-namespace:MyControls" > 
    <UserControl.Resources> 
     <local:MyCustomCollection x:Key="MyKey"> 
      <local:MyCustomItem> 
      </local:MyCustomItem> 
     </local:MyCustomCollection> 
    </UserControl.Resources> 
</UserControl> 

的問題是,我得到了「類型‘MyCustomCollection的設計者是一個錯誤’不支持直接的內容」。我已經嘗試設置ContentProperty建議在MSDN中,但無法弄清楚要設置它。我使用的自定義集合對象如下,非常簡單。我試過Item,Items和MyCustomItem,想不到還有什麼可以嘗試的。

<ContentProperty("WhatGoesHere?")> _ 
Public Class MyCustomCollection 
    Inherits ObservableCollection(Of MyCustomItem) 
End Class 

任何關於我哪裏出錯的線索都會感激不盡。同時也提示如何深入研究WPF對象模型以查看運行時暴露的屬性,我可能也可以通過這種方式來弄清楚。

問候

瑞安

回答

5

你有那將代表你的類的內容屬性的名稱來初始化ContentPropertyAttribute。在你的情況下,因爲你從ObservableCollection繼承,那將是Items屬性。不幸的是,Items屬性是隻讀的,這是不允許的,因爲Content屬性必須有一個setter。所以,你必須定義圍繞項目自定義包裝財產和使用,在你的屬性 - 像這樣:

public class MyCustomItem 
{ } 

[ContentProperty("MyItems")] 
public class MyCustomCollection : ObservableCollection<MyCustomItem> 
{ 
    public IList<MyCustomItem> MyItems 
    { 
     get { return Items; } 
     set 
     { 
      foreach (MyCustomItem item in value) 
      { 
       Items.Add(item); 
      } 
     } 
    } 
} 

而且你應該沒事。對不起,在C#中,當你的例子是在VB中,但是我真的很喜歡VB,並且無法得到這樣簡單的東西......無論如何,轉換它是很簡單的,所以 - 希望有所幫助。

+0

看起來不錯,但關於你的二傳手的問題在那裏。難道這不會不斷加入集合並導致異常? 另外,爲什麼IList和不是ObservableCollection? 謝謝 – 2008-12-10 17:08:59

相關問題