簡體   English   中英

WPF/MVVM 在運行時動態加載視圖

[英]WPF/MVVM Load a View dynamically at runtime

我有一個簡單的 WPF 應用程序,如下所示:

在此處輸入圖片說明

我還創建了 3 個不同的視圖:

  • 細節類型1.xaml
  • 細節類型2.xaml
  • 細節類型3.xaml

每個視圖都有自己的 ViewModel

父視圖.xaml

...
<!-- Detail Area -->
<GroupBox x:Name="groupDetails" Grid.Column="0" Header="Details"
                      HorizontalAlignment="Stretch"
                      Grid.Row="0" VerticalAlignment="Stretch">
   <GroupBox.Resources>
        <ResourceDictionary>
             <DataTemplate DataType="{x:Type vm:DetailType1ViewModel}">
                  <views:DetailType1View/>
             </DataTemplate>
             <DataTemplate DataType="{x:Type vm:DetailType2ViewModel}">
                  <views:DetailType2View/>
             </DataTemplate>
        </ResourceDictionary>
   </GroupBox.Resources>
   <ContentPresenter DataContext="{Binding}" Content="{Binding Path=BaseTypeViewModel}" />
</GroupBox>
...

父視圖模型.cs

...
public BaseViewModel BaseTypeViewModel
{
    get { return GetValue<BaseViewModel>(); }
    set
    {
        SetValue(value);
    }
}

private void ShowDetailDialog()
{
    var vm = GetViewModelByID(SelectedID);
    BaseTypeViewModel = vm;
}

private BaseViewModel GetViewModelByID(int Id)
{
    switch (Id)
    {
        case 1:
            return IoC.Get<DetailType1ViewModel>();
        case 2:
            return IoC.Get<DetailType2ViewModel>();
    }
}
...

DetailType1ViewModel.cs

public class DetailType1ViewModel : BaseViewModel
{
    ...
}

我的問題是:

每次雙擊左側窗格中的 DataGrid 行時,我想根據所選 ID 將上述視圖之一加載到詳細信息區域。 那么可以使用哪些技術呢? 如果您能向我展示代碼示例,那就太好了。

感謝大家的幫助。

  1. <ResourceDictionary>為要在詳細信息區域中顯示的每個 ViewModel 創建一個<DataTemplate> (使用正確的DataType={x:Type local:DetailTypeViewModelX} )。
  2. 確保此<ResourceDictionary>合並到詳細信息區域的祖先中。 一個可能的位置是<Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="..." />
  3. 將詳細信息區域的DataContext綁定到要顯示的ViewModel 的實例。
  4. 在要顯示步驟 1 中<DataTemplate>內容的詳細信息區域中創建一個<ContentPresenter Content="{Binding}" />

這應該有效並遵循 MVVM 的整體概念。

暫無
暫無

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

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