2017-07-26 52 views
2

我正在嘗試創建一個從Xaml創建的DependencyObject。 它具有像這樣定義List<object>類型的DependencyProperty如何在UWP中爲集合類型定義`DependencyProperty`?

public List<object> Map 
    { 
     get { return (List<object>)GetValue(MapProperty); } 
     set { SetValue(MapProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Map. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MapProperty = 
     DependencyProperty.Register("Map", typeof(List<object>), typeof(MyConverter), new PropertyMetadata(null)); 

的Xaml:

 <MyConverter x:Key="myConverter"> 
      <MyConverter.Map> 
       <TextPair First="App.Blank" Second ="App.BlankViewModel"/> 
      </MyConverter.Map> 
     </MyConverter> 

我不斷接收Cannot add instance of type 'UwpApp.Xaml.TextPair' to a collection of type 'System.Collections.Generic.List<Object>。 什麼會導致此錯誤?謝謝。

+1

此錯誤的原因很簡單:您定義了類型爲'List '的'Property'並設置了不是正確類型的'TextPair'類型的值。 – Fruchtzwerg

+0

@Fruchtzwerg,我試過你的暗示,但它仍然失敗。 –

+0

我很困惑,因爲我沒有提出任何建議。那麼你嘗試了什麼? – Fruchtzwerg

回答

5

您將DependencyProperty的類型定義爲typeof(List<object>)。這意味着該屬性需要這種類型。由於List<object>不是 a TextPair我們需要更通用。而不是使用特殊的通用列表類型,只需使用IList作爲類型,並添加new List<object>()作爲默認值。這應該可以解決你的問題。

public IList Map 
{ 
    get { return (IList)GetValue(MapProperty); } 
    set { SetValue(MapProperty, value); } 
} 

public static readonly DependencyProperty MapProperty = 
    DependencyProperty.Register("Map", typeof(IList), 
     typeof(MyConverter), new PropertyMetadata(new List<object>())); 

編輯: 貌似UWP表現略高於WPF不同。要在UWP中運行此代碼,您需要使用通用IList<object>而不是IList作爲屬性類型。

+1

就是這樣。另外,如果你在你的'MyConverter'類上放了'[ContentProperty(Name = nameof(Map))]',你可以從你的xaml中移除''。 –

+0

我得到'XamlCompiler錯誤WMC0015:無法將'TextPair'分配到屬性'Map',類型必須分配給'IList'' –

+2

@AndriyShevchenko嘗試將'IList'更改爲'IList '。 –

相關問題