この記事は転載から
著者:Ryzen Adorer
前の記事:. NET Core 3 WPF MVVMフレームワークPrismシリーズのゾーンマネージャ
原文へのリンク:https//www.cnblogs.com/ryzen/p/12605347.html
この記事では、. NET Core3環境でMVVMフレームワークPrismを使用してゾーンマネージャを使用したビュー管理方法を説明します。
1. エリアマネージャーの一覧
以前のPrismシリーズでは標準的なPrismプロジェクトを構築しました。この記事では、以前のプロジェクトで使用されたゾーンマネージャを使用してビューをより良く管理する方法について説明します。

ここでわかることは、ゾーンマネージャRegionMannagerがコントロールのゾーンを作成する際の大まかなポイントです。
- Regionを作成するコントロールにはRegionAdapterアダプタが必要です。
- RegionはRegionAdapterコントロールに依存します。
実際、私は公式の紹介とソースコードを見に行き、デフォルトのRegionAdapterは3つあり、カスタムRegionAdapterもサポートしているので、公式のモデル図の間に少し補足をしました。

2. エリア作成とビュー注入
前のプロジェクトのリージョン分割と、リージョンを作成してリージョンにビューを注入する方法を見てみましょう。

メインウィンドウ全体を4つの領域に分けました。
- ShowSearchPatientRegion ShowSearchPatientビューが注入されました。
- PatientListRegion:PatientListビューを挿入します。
- FlyoutRegion:PatientDetailビューとSearchMedicineビューを注入
- ShowSearchPatientRegion ShowSearchPatientビューが注入されました。
Prismでは、リージョン作成とビューインジェクションを実装する2つの方法があります。
- ViewDiscovery
- ViewInjection
2.1. ViewDiscovery
PatientListRegionの作成とビューインジェクションのコードを傍受しました(デモソースコードを詳しく見ることができます)。
MainWindow.xaml:
<ContentControl
Grid.Row="2"
prism:RegionManager.RegionName="PatientListRegion"
Margin="10"
/>
これはバックグラウンドでMainWindows.csと同じです:
RegionManager.SetRegionName(ContentControl, "PatientListRegion");
PatientModule.cs:
public class PatientModule : IModule
{
public void OnInitialized(IContainerProvider containerProvider)
{
var regionManager = containerProvider.Resolve<IRegionManager>();
//PatientList
regionManager.RegisterViewWithRegion(RegionNames.PatientListRegion, typeof(PatientList));
//PatientDetail-Flyout
regionManager.RegisterViewWithRegion(RegionNames.FlyoutRegion, typeof(PatientDetail));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
2.2. ViewInjection
MainWindowフォームのLoadedイベントでViewInjectionを使用してView PatientListを注入します。
MainWindow.xaml:
<i:Interaction.Triggers> <i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadingCommand}"/>
/i:EventTrigger>
</i:Interaction.Triggers>
MainWindowViewModel.cs:
private IRegionManager _regionManager;
private IRegion _paientListRegion;
private PatientList _patientListView;
private DelegateCommand _loadingCommand;
public DelegateCommand LoadingCommand =>
_loadingCommand ?? (_loadingCommand = new DelegateCommand(ExecuteLoadingCommand));
void ExecuteLoadingCommand()
{
_regionManager = CommonServiceLocator.ServiceLocator.Current.GetInstance<IRegionManager>();
_paientListRegion = _regionManager.Regions[RegionNames.PatientListRegion];
_patientListView = CommonServiceLocator.ServiceLocator.Current.GetInstance<PatientList>();
_paientListRegion.Add(_patientListView);
}
ViewDiscoveryメソッドは自動的にビューをインスタンス化してロードすることであり、ViewInjectionメソッドはビューの注入とビューのロードタイミングを手動で制御することができます(上記の例はLoadedイベントを通じてです)、両方の公式推奨シナリオは次のとおりです:
ViewDiscovery:
- ビューの自動ロードが必要または必要
- ビューの個々のインスタンスが領域にロードされます。
ViewInjection:
- ビューを作成および表示するタイミングを明示的またはプログラムで制御する必要がある場合、または領域からビューを削除する必要がある場合
- 領域内に同じビューの複数のインスタンスを表示する必要があり、各ビューのインスタンスは異なるデータにバインドされている
- ビューを追加する領域のどのインスタンスを制御する必要がありますか
- アプリケーションはナビゲーションAPIを使用します後述
3. アクティブ化ビューと無効化ビュー
3.1.活性化と非活性化
まず、PatientListビューとMedicineMainContentビューの有効化を制御する必要があります。
MainWindow.xaml:
<StackPanel Grid.Row="1">
<button
Content="Load MedicineModule"
FontSize="25"
Margin="5"
Command="{Binding LoadMedicineModuleCommand}"
/>
<UniformGrid Margin="5">
<button
Content="ActivePaientList"
Margin="5"
Command="{Binding ActivePaientListCommand}"
/>
<button
Content="DeactivePaientList"
Margin="5"
Command="{Binding DeactivePaientListCommand}"
/>
<button
Content="ActiveMedicineList"
Margin="5"
Command="{Binding ActiveMedicineListCommand}"
/>
<button
Content="DeactiveMedicineList"
Margin="5"
Command="{Binding DeactiveMedicineListCommand}"
/>
</UniformGrid>
</StackPanel>
<ContentControl
Grid.Row="2"
prism:RegionManager.RegionName="PatientListRegion"
Margin="10"
/>
<ContentControl
Grid.Row="3"
prism:RegionManager.RegionName="MedicineMainContentRegion"
/>
MainWindowViewModel.cs:
private IRegionManager _regionManager;
private IRegion _paientListRegion;
private IRegion _medicineListRegion;
private PatientList _patientListView;
private MedicineMainContent _medicineMainContentView;
private bool _isCanExcute = false;
public bool IsCanExcute
{
get { return _isCanExcute; }
set { SetProperty(ref _isCanExcute, value); }
}
private DelegateCommand _loadingCommand;
public DelegateCommand LoadingCommand =>
_loadingCommand ?? (_loadingCommand = new DelegateCommand(ExecuteLoadingCommand));
private DelegateCommand _activePaientListCommand;
public DelegateCommand ActivePaientListCommand =>
_activePaientListCommand ?? (_activePaientListCommand = new DelegateCommand(ExecuteActivePaientListCommand));
private DelegateCommand _deactivePaientListCommand;
public DelegateCommand DeactivePaientListCommand =>
_deactivePaientListCommand ?? (_deactivePaientListCommand = new DelegateCommand(ExecuteDeactivePaientListCommand));
private DelegateCommand _activeMedicineListCommand;
public DelegateCommand ActiveMedicineListCommand =>
_activeMedicineListCommand ?? (_activeMedicineListCommand = new DelegateCommand(ExecuteActiveMedicineListCommand)
.ObservesCanExecute(() => IsCanExcute));
private DelegateCommand _deactiveMedicineListCommand;
public DelegateCommand DeactiveMedicineListCommand =>
_deactiveMedicineListCommand ?? (_deactiveMedicineListCommand = new DelegateCommand(ExecuteDeactiveMedicineListCommand)
.ObservesCanExecute(() => IsCanExcute));
private DelegateCommand _loadMedicineModuleCommand;
public DelegateCommand LoadMedicineModuleCommand =>
_loadMedicineModuleCommand ?? (_loadMedicineModuleCommand = new DelegateCommand(ExecuteLoadMedicineModuleCommand));
/// <summary>
/// 窗体加载事件
/// </summary>
void ExecuteLoadingCommand()
{
_regionManager = CommonServiceLocator.ServiceLocator.Current.GetInstance<IRegionManager>();
_paientListRegion = _regionManager.Regions[RegionNames.PatientListRegion];
_patientListView = CommonServiceLocator.ServiceLocator.Current.GetInstance<PatientList>();
_paientListRegion.Add(_patientListView);
_medicineListRegion = _regionManager.Regions[RegionNames.MedicineMainContentRegion];
}
/// <summary>
/// 失效medicineMainContent视图
/// </summary>
void ExecuteDeactiveMedicineListCommand()
{
_medicineListRegion.Deactivate(_medicineMainContentView);
}
/// <summary>
/// 激活medicineMainContent视图
/// </summary>
void ExecuteActiveMedicineListCommand()
{
_medicineListRegion.Activate(_medicineMainContentView);
}
/// <summary>
/// 失效patientList视图
/// </summary>
void ExecuteDeactivePaientListCommand()
{
_paientListRegion.Deactivate(_patientListView);
}
/// <summary>
/// 激活patientList视图
/// </summary>
void ExecuteActivePaientListCommand()
{
_paientListRegion.Activate(_patientListView);
}
/// <summary>
/// 加载MedicineModule
/// </summary>
void ExecuteLoadMedicineModuleCommand()
{
_moduleManager.LoadModule("MedicineModule");
_medicineMainContentView = (MedicineMainContent)_medicineListRegion.Views
.Where(t => t.GetType() == typeof(MedicineMainContent)).FirstOrDefault();
this.IsCanExcute = true;
}
効果は以下のとおり。

3.2.ビューのアクティブ化ステータスのモニタリング
Prismはビューのアクティブ状態の監視もサポートしており,ViewからIActiveAwareを継承することで実現しており,MedicineMainContentビューのアクティブ状態の監視を例にとる.
MedicineMainContentViewModel.cs:
public class MedicineMainContentViewModel : BindableBase,IActiveAware
{
public event EventHandler IsActiveChanged;
bool _isActive;
public bool IsActive
{
get { return _isActive; }
set
{
_isActive = value;
if (_isActive)
{
MessageBox.Show("视图被激活了");
}
else
{
MessageBox.Show("视图失效了");
}
IsActiveChanged?.Invoke(this, new EventArgs());
}
}
}

3.3.追加と削除。
上記の例はContentControlを使用していますが、ItemsControlの例を使用しています。
MainWindow.xaml:
<metro:MetroWindow.RightWindowCommands>
<metro:WindowCommands x:Name="rightWindowCommandsRegion" />
</metro:MetroWindow.RightWindowCommands>
MainWindow.cs:
public MainWindow()
{
InitializeComponent();
var regionManager= ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager != null)
{
SetRegionManager(regionManager, this.flyoutsControlRegion, RegionNames.FlyoutRegion);
//创建WindowCommands控件区域
SetRegionManager(regionManager, this.rightWindowCommandsRegion, RegionNames.ShowSearchPatientRegion);
}
}
void SetRegionManager(IRegionManager regionManager, DependencyObject regionTarget, string regionName)
{
RegionManager.SetRegionName(regionTarget, regionName);
RegionManager.SetRegionManager(regionTarget, regionManager);
}
ShowSearchPatient.xaml:
<StackPanel
x:Class="PrismMetroSample.MedicineModule.Views.ShowSearchPatient"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:const="clr-namespace:PrismMetroSample.Infrastructure.Constants;assembly=PrismMetroSample.Infrastructure"
Orientation="Horizontal"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
prism:ViewModelLocator.AutoWireViewModel="True"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding ShowSearchLoadingCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<CheckBox IsChecked="{Binding IsShow}" />
<button
Command="{Binding ApplicationCommands.ShowCommand}"
CommandParameter="{x:Static const:FlyoutNames.SearchMedicineFlyout}"
>
<StackPanel Orientation="Horizontal">
<image
Height="20"
Source="pack://application:,,,/PrismMetroSample.Infrastructure;Component/Assets/Photos/按钮.png"
/>
<TextBlock
Text="Show"
FontWeight="Bold"
FontSize="15"
VerticalAlignment="Center"
/>
</StackPanel>
</button>
</StackPanel>
ShowSearchPatientViewModel.cs:
private IApplicationCommands _applicationCommands;
private readonly IRegionManager _regionManager;
private ShowSearchPatient _showSearchPatientView;
private IRegion _region;
public IApplicationCommands ApplicationCommands
{
get { return _applicationCommands; }
set { SetProperty(ref _applicationCommands, value); }
}
private bool _isShow=true;
public bool IsShow
{
get { return _isShow=true; }
set
{
SetProperty(ref _isShow, value);
if (_isShow)
{
ActiveShowSearchPatient();
}
else
{
DeactiveShowSearchPaitent();
}
}
}
private DelegateCommand _showSearchLoadingCommand;
public DelegateCommand ShowSearchLoadingCommand =>
_showSearchLoadingCommand ?? (_showSearchLoadingCommand = new DelegateCommand(ExecuteShowSearchLoadingCommand));
void ExecuteShowSearchLoadingCommand()
{
_region = _regionManager.Regions[RegionNames.ShowSearchPatientRegion];
_showSearchPatientView = (ShowSearchPatient)_region.Views
.Where(t => t.GetType() == typeof(ShowSearchPatient)).FirstOrDefault();
}
public ShowSearchPatientViewModel(IApplicationCommands applicationCommands,IRegionManager regionManager)
{
this.ApplicationCommands = applicationCommands;
_regionManager = regionManager;
}
/// <summary>
/// 激活视图
/// </summary>
private void ActiveShowSearchPatient()
{
if (!_region.ActiveViews.Contains(_showSearchPatientView))
{
_region.Add(_showSearchPatientView);
}
}
/// <summary>
/// 失效视图
/// </summary>
private async void DeactiveShowSearchPaitent()
{
_region.Remove(_showSearchPatientView);
await Task.Delay(2000);
IsShow = true;
}
効果は以下のとおり。

WindowCommandsの継承チェーンは、WindowCommands <--ToolBar <--HeaderedItemsControl <--ItemsControlです。したがって、PrismのデフォルトのアダプタにはItemsControlRegionAdapterがあるため、そのサブクラスもその動作を継承します。
ここで要約します。
- モジュール化すると、モジュールがロードされた後、ビューがゾーンに注入されなくなりますMedicineModuleビューのロード順序を参照。
- Content Control Contentは1つしか表示できないため、ActivateメソッドとDeactivateメソッドを使用してリージョン内で表示するビューを制御でき、その動作はContentControl RegionAdapterアダプタによって制御されます。
- ItemsControlコントロールとそのサブコントロールは、コレクションビューを表示するため、デフォルトではすべてのコレクションビューがアクティブになり、ActivateとDeactivateで制御することはできませんエラーが報告されます。AddとRemoveで表示するビューを制御します。その動作はItemsControlRegionAdapterアダプタによって制御されます。
- SelectorコントロールはItemsControlから継承されているため、SelectorRegionAdapterアダプタはItemsControl RegionAdapterアダプタと同一です。
- IActiveAwareインターフェイスを継承してビューのアクティブ化状態を監視できる
4. カスタムゾーンアダプタ
ゾーンマネージャ全体のモデル図で説明したように、Prismには3つのデフォルトゾーンアダプタがあります:ItemsControl RegionAdapter、ContentControl RegionAdapter、SelectorRegionAdapterがあり、カスタムゾーンアダプタをサポートしています。
4.1.カスタムアダプターの作成
新しいクラスUniformGridRegionAdapter.cs
public class UniformGridRegionAdapter : RegionAdapterBase<UniformGrid>
{
public UniformGridRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
{
}
protected override void Adapt(IRegion region, UniformGrid regionTarget)
{
region.Views.CollectionChanged += (s, e) =>
{
if (e.Action==System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
foreach (FrameworkElement element in e.NewItems)
{
regionTarget.Children.Add(element);
}
}
};
}
protected override IRegion CreateRegion()
{
return new AllActiveRegion();
}
}
4.2.マッピングの登録
App.cs:
protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
{
base.ConfigureRegionAdapterMappings(regionAdapterMappings);
//为UniformGrid控件注册适配器映射
regionAdapterMappings.RegisterMapping(typeof(UniformGrid),Container.Resolve<UniformGridRegionAdapter>());
}
4.3.コントロールの領域の作成
MainWindow.xaml:
<UniformGrid
Margin="5"
prism:RegionManager.RegionName="UniformContentRegion"
Columns="2"
>
<button
Content="ActivePaientList"
Margin="5"
Command="{Binding ActivePaientListCommand}"
/>
<button
Content="DeactivePaientList"
Margin="5"
Command="{Binding DeactivePaientListCommand}"
/>
<button
Content="ActiveMedicineList"
Margin="5"
Command="{Binding ActiveMedicineListCommand}"
/>
<button
Content="DeactiveMedicineList"
Margin="5"
Command="{Binding DeactiveMedicineListCommand}"
/>
</UniformGrid>
4.4.領域にビューを注入する
ViewInjectionメソッドを使用します:
MainWindowViewModel.cs
void ExecuteLoadingCommand()
{
_regionManager = CommonServiceLocator.ServiceLocator.Current.GetInstance<IRegionManager>();
var uniformContentRegion = _regionManager.Regions["UniformContentRegion"];
var regionAdapterView1 = CommonServiceLocator.ServiceLocator.Current.GetInstance<RegionAdapterView1>();
uniformContentRegion.Add(regionAdapterView1);
var regionAdapterView2 = CommonServiceLocator.ServiceLocator.Current.GetInstance<RegionAdapterView2>();
uniformContentRegion.Add(regionAdapterView2);
}
効果は以下の通り。

UniformGrid用のリージョンアダプタを作成し、登録後にUniformGridコントロール用のリージョンを作成することができ、インジェクションビューはリージョンアダプタがないとエラーが発生することを示しています。次の記事では、リージョンベースのプリズムナビゲーションシステムについて説明します。
5. ソースコードソース
最后,附上整个 demo 的源代码:PrismDemo 源码