簡體   English   中英

使用Prism根據對象類型將視圖注入ItemsControl

[英]Inject views into ItemsControl depending on object type using Prism

我有一個返回BaseItem類型數組的服務。 BaseItem具有N個子類型。 我從視圖模型開始在WPF應用程序(Prism,MVVM)中使用此服務。 在此視圖模型的構造函數中,我填充了BaseItem類型的可觀察集合:

public CurrentViewModel(IDataService dataService) 
{ 
    _dataService = dataService

    var baseItems = _dataService.GetAllItems(); // there are many kinds of BaseItems
    _baseItems = new ObservableCollection<BaseItem>(baseItems.ToList()); 
} 

到現在為止還挺好。 在我的CurrentView我有一個ItemsControl綁定到此集合。 在此控件中,我想通過使用另一個View (及其視圖模型)來呈現每個BaseItem

直到現在,我無法使用DataTemplateSelector因為無法在其中定義每個DataTemplate,我正在加載N個模塊(其中包含從BaseItem繼承的類),PRISM從特定文件夾中動態加載它們。

我使用的是View Model first方法,還需要其他哪些替代方案來實現此方案?

只需從您的模塊中將datatemplate資源作為資源字典導出,特定子類型為DataType。 我使用MEF進行此操作,並在我的主應用程序中將此資源字典合並。 現在,WPF知道所有數據模板/視圖,並且itemscontrol可以根據需要呈現每個子類型的viewmodel。

編輯:

modul1.dll

public class Modul1VM : BaseItemViewModel {} 

用MEF導出的modul1.dll中的ResourceDictionary

<DataTemplate DataType="{x:Type local: Modul1VM}">
 <view:Yourmodul1View/>
</DataTemplate>

modul2.dll

public class Modul2VM : BaseItemViewModel {} 

用MEF導出的modul2.dll中的ResourceDictionary

<DataTemplate DataType="{x:Type local: Modul2VM}">
 <view:Yourmodul2View/>
</DataTemplate>

您的主要應用

  • 合並所有導出的Resourcedictionarys

app.xaml.cs

 [ImportMany("Resourcen", typeof (ResourceDictionary))] 
 private IEnumerable<ResourceDictionary> _importResourcen;

啟動時

 foreach (var resourceDictionary in _importResourcen)
 {
     this.Resources.MergedDictionaries.Add(resourceDictionary);
 }

您的itemscontrol只需要BaseItemViewModels的集合作為itemssource

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM