この記事は転載から
著者:Ryzen Adorer
前の記事:. NET Core 3 WPF MVVMフレームワークPrismシリーズのダイアログサービス
原文へのリンク:https//www.cnblogs.com/ryzen/p/12771986.html
この記事では、. NET Core3環境でMVVMフレームワークPrismのダイアログサービスを使用する方法を説明します。Prismシリーズの最後の記事となります。
.NET Core 3 WPF MVVM 框架 Prism 系列之文章索引
1. ダイアログ·サービス
Prismでは、ダイアログサービスはIDialogAwareインターフェイスを介して実装されています。
public interface IDialogAware
{
bool CanCloseDialog();
void OnDialogClosed();
void OnDialogOpened(IDialogParameters parameters);
string Title { get; set; }
event Action<IDialogResult> RequestClose;
}
- CanCloseDialog関数は、フォームが閉じるかどうかを決定します。
- OnDialogClosed関数は、CanCloseDialog関数に応じて、フォームが閉じられたときにトリガーされます。
- OnDialogOpened関数がフォームを開いているときに起動し、フォームLoadedイベントよりも前に起動します。
- タイトルはフォームのタイトルです。
- RequestCloseは、フォームの閉じを制御する閉じるイベントです。
2.1.ダイアログのViewとViewModelの作成
AlertDialog.xaml:
<UserControl
x:Class="PrismMetroSample.Shell.Views.Dialogs.AlertDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PrismMetroSample.Shell.Views.Dialogs"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
Width="350"
Height="120"
prism:ViewModelLocator.AutoWireViewModel="True"
>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<image
Source="pack://application:,,,/PrismMetroSample.Infrastructure;Component/Assets/Photos/alter.png"
Height="40"
UseLayoutRounding="True"
RenderOptions.BitmapScalingMode="HighQuality"
/>
<TextBlock
Grid.Column="1"
Text="{Binding Message}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Grid.Row="0"
TextWrapping="Wrap"
FontSize="15"
FontFamily="Open Sans"
/>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<button
Margin="5"
Foreground="White"
FontSize="12"
Background="#5cb85c"
Command="{Binding CloseDialogCommand}"
CommandParameter="true"
Content="Yes"
Width="64"
Height="28"
HorizontalAlignment="Right"
Grid.Row="1"
/>
<button
Grid.Column="1"
Margin="5"
Foreground="White"
FontSize="12"
Background="#d9534f"
Command="{Binding CloseDialogCommand}"
CommandParameter="false"
Content="No"
Width="64"
Height="28"
HorizontalAlignment="Left"
Grid.Row="1"
/>
</Grid>
</Grid>
</UserControl>
AlertDialogViewModel.cs:
public class AlertDialogViewModel : BindableBase, IDialogAware
{
private DelegateCommand<string> _closeDialogCommand;
public DelegateCommand<string> CloseDialogCommand =>
_closeDialogCommand ?? (_closeDialogCommand = new DelegateCommand<string>(ExecuteCloseDialogCommand));
void ExecuteCloseDialogCommand(string parameter)
{
ButtonResult result = ButtonResult.None;
if (parameter?.ToLower() == "true")
result = ButtonResult.Yes;
else if (parameter?.ToLower() == "false")
result = ButtonResult.No;
RaiseRequestClose(new DialogResult(result));
}
//触发窗体关闭事件
public virtual void RaiseRequestClose(IDialogResult dialogResult)
{
RequestClose?.Invoke(dialogResult);
}
private string _message;
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
private string _title = "Notification";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public event Action<IDialogResult> RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
}
public void OnDialogOpened(IDialogParameters parameters)
{
Message = parameters.GetValue<string>("message");
}
}
2.2.登録ダイアログの登録
App.cs:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterDialog<AlertDialog, AlertDialogViewModel>();
}
还可以注册时起名字:
Copy
containerRegistry.RegisterDialog<AlertDialog, AlertDialogViewModel>(“alertDialog”);
2.3.ダイアログサービスの使用
CreateAccountViewModel.cs修正セクション
public CreateAccountViewModel(IRegionManager regionManager, IDialogService dialogService)
{
_regionManager = regionManager;
_dialogService = dialogService;
}
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
if (!string.IsNullOrEmpty(RegisteredLoginId) && this.IsUseRequest)
{
_dialogService.ShowDialog("AlertDialog", new DialogParameters($"message={"是否需要用当前注册的用户登录?"}"), r =>
{
if (r.Result == ButtonResult.Yes)
navigationContext.Parameters.Add("loginId", RegisteredLoginId);
});
}
continuationCallback(true);
}
効果は以下のとおり。

IDialog ServiceインターフェイスのShowDialog関数を呼び出すことで呼び出します。このインターフェイスの定義は次のとおりです。
public interface IDialogService : Object
{
Void Show(String name, IDialogParameters parameters, Action<IDialogResult> callback);
Void ShowDialog(String name, IDialogParameters parameters, Action<IDialogResult> callback);
}
show関数とShowDialog関数は同じパラメータであることがわかりますが、使用シナリオが異なります。
- name:呼び出したいダイアログビューの名前。エイリアスを登録する場合は、エイリアスのみを使用して呼び出すことができます。
- parameters IdialogParametersインタフェース型パラメータ、受信プロンプトメッセージ。通常は$"message="形式で、ViewModelのOnDialogOpened関数がIdialogParametersインタフェースのGetValue関数で取得します。
- callback:戻り値のないコールバック関数を渡す場合。
2. ダイアログボックスのフォームのカスタマイズ
上記で見ることができるように、ダイアログボックスのフォームはWPF独自のフォームですが、例えば、ウィンドウのアイコンを削除し、最大化、最小化、閉じを保持したり、サードパーティ製のフォームコントロールを使用したりするなど、独自のフォームを使用する場合、Prismはダイアログボックスのフォームを登録し、別のダイアログボックスのビューを介してダイアログボックスのフォームのスタイルを指定することで、異なるダイアログボックスを柔軟に実装することができます。以下では、操作方法を見てみましょう:
2.1.カスタムダイアログボックスフォームの登録
新しいフォームDialogWindows.xamlを作成します。
<Window
x:Class="PrismMetroSample.Shell.Views.Dialogs.DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PrismMetroSample.Shell.Views.Dialogs"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
>
<Grid> </Grid>
</Window>
DialogWindow.xaml.cs:
public partial class DialogWindow : Window, IDialogWindow
{
public DialogWindow()
{
InitializeComponent();
}
protected override void OnSourceInitialized(EventArgs e)
{
WindowHelp.RemoveIcon(this);//使用win32函数去除Window的Icon部分
}
public IDialogResult Result { get; set; }
}
App.cs:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterDialogWindow<DialogWindow>();//注册自定义对话框窗体
}
2.2.ダイアログボックスのフォームStyleのカスタマイズ
AlertDialog.xaml:
<prism:Dialog.WindowStyle>
<style TargetType="Window">
<Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterScreen" />
<Setter Property="ShowInTaskbar" Value="False"/>
<Setter Property="SizeToContent" Value="WidthAndHeight"/>
</style>
</prism:Dialog.WindowStyle>
効果は以下の通りです

フォームスタイルをすべて削除し、AlertDialog.xamlを変更する方法
<prism:Dialog.WindowStyle>
<style TargetType="Window">
<Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterScreen" />
<Setter Property="ShowInTaskbar" Value="False"/>
<Setter Property="SizeToContent" Value="WidthAndHeight"/>
<Setter Property="WindowStyle" Value="None"/>
</style>
</prism:Dialog.WindowStyle>
以下のようになります:

最終的な結果は以下の通りです:

3. 概要まとめまとめ
Prismのダイアログサービスを使用すると、IDialog Serviceインターフェイスを介してダイアログのポップアップロジックを統一的に管理することができ、依存性注入モードを使用することができます。以前にいくつかのカスタムダイアログを定義したい場合は、View 部分に強く依存し、異なるダイアログのフォームスタイルをカスタマイズすることで、ある程度の柔軟性を達成することができます。2つの異なるダイアログ·スタイルを使用した最終効果のデモなど、. NET Core3.x Prismシリーズの記事が完成しました。
4. ソースコードソース
最后,附上整个 demo 的源代码:PrismDemo 源码