WPF:蒙版弹出窗体

一般设计

<Grid>
    <Grid x:Name="gridMain">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" x:Name="btnWindow1" Width="50" Height="40" Content="子窗体1" Click="btnOpen_Click"></Button>
        <Button Grid.Column="1" x:Name="btnWindow2" Width="50" Height="40" Content="子窗体2" Click="btnOpen2_Click"></Button>
    </Grid>
    <Grid x:Name="gridChidWindow" Visibility="Hidden">
        <Grid Background="DarkGray" Opacity="0.8"></Grid>
        <Grid x:Name="gridChidWindowContent" Margin="40,80,40,40">
            <Border BorderBrush="Red" BorderThickness="2"></Border>
        </Grid>
        <Button x:Name="btnChidWindowClose" Content="CLose" Width="40" Height="40" Margin="0,60,20,20" Background="LightGray" HorizontalAlignment="Right" VerticalAlignment="Top" Click="btnChidWindowClose_Click"></Button>
    </Grid>
    <Grid x:Name="gridChidWindow2" Visibility="Hidden">
        <Grid Background="DarkGray" Opacity="0.8"></Grid>
        <Grid x:Name="gridChidWindowContent2" Margin="40,80,40,40">
            <Border BorderBrush="Blue" BorderThickness="2"></Border>
        </Grid>
        <Button x:Name="btnChidWindowClose2" Content="CLose" Width="40" Height="40" Margin="0,60,20,20" Background="LightGray" HorizontalAlignment="Right" VerticalAlignment="Top" Click="btnChidWindowClose2_Click"></Button>
    </Grid>
</Grid>
private void btnChidWindowOpen_Click(object sender, RoutedEventArgs e)
{
    gridChidWindow.Visibility = Visibility.Visible;
}
private void btnChidWindowClose_Click(object sender, RoutedEventArgs e)
{
    gridChidWindow.Visibility = Visibility.Hidden;
}


封装成用户控件


xmlns:ws="https://wesson.com/WessonControl"
<Grid Name="gridContentBackground" VerticalAlignment="Stretch">
    <Grid Background="DarkGray" Opacity="0.8"></Grid>
    <Grid Name="gridContent" Margin="{Binding FormMargin, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"></Grid>

    <Grid HorizontalAlignment="Right" VerticalAlignment="Top" ButtonBase.Click="Grid_Click">
       <Border x:Name="brdClose" Width="25" Height="25" Margin="10" Background="Black" ws:BorderElement.Circular="True"/>
       <Button x:Name="btnClose" HorizontalAlignment="Right" VerticalAlignment="Top" Width="25" Height="25"  Margin="10"  Padding="0"
           Background="Transparent" Foreground="LightGray" Style="{StaticResource ButtonIcon}" ws:IconElement.Geometry="{StaticResource ClosePopGeometry}"
           Content="Close子窗口" ToolTip="关闭" Click="BtnContentClose_Click"  />
    </Grid> 
</Grid>
using System;
using System.Windows;
using System.Windows.Controls;
/// <summary>
/// 蒙版弹出窗体
/// </summary>
public partial class UC_ChildForm : UserControl
{
    private readonly static Thickness _defaultThickness = new Thickness(20);
    private readonly static Type _classType = typeof(UC_ChildForm);

    /// <summary>
    /// 弹出窗体相对边距
    /// </summary>
    public Thickness FormMargin
    {
        get { return (Thickness)GetValue(FormMarginProperty); }
        set { SetValue(FormMarginProperty, value); }
    }
    public static readonly DependencyProperty FormMarginProperty =
        DependencyProperty.Register("FormMargin", typeof(Thickness), _classType, new PropertyMetadata(_defaultThickness, OnFormMarginChanged));
    private static void OnFormMarginChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ctl = (UC_ChildForm)d;
        ctl.OnFormMarginChanged((Thickness)e.NewValue);
    }
    private void OnFormMarginChanged(Thickness newValue)
    {
        brdClose.Margin = new Thickness(10, newValue.Top - 10, newValue.Right - 10, 10);
        btnClose.Margin = new Thickness(10, newValue.Top - 10, newValue.Right - 10, 10);
    }

    /// <summary>
    /// 弹出窗体的宽
    /// </summary>
    public double FormWidth
    {
        get { return (double)GetValue(FormWidthProperty); }
        set { SetValue(FormWidthProperty, value); }
    }
    public static readonly DependencyProperty FormWidthProperty =
        DependencyProperty.Register("FormWidth", typeof(double), _classType, new PropertyMetadata(0.0, OnFormWidthChanged));
    private static void OnFormWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ctl = (UC_ChildForm)d;
        ctl.OnFormWidthChanged((double)e.NewValue);
    }
    private void OnFormWidthChanged(double width)
    {
        if (gridContent.Children.Count == 0) return;
        // 解决关闭按钮不随父窗口大小变化问题
        var old = FormMargin;
        var marginHori = (this.ActualWidth - width) / 2;
        old.Left = marginHori;
        old.Right = marginHori;
        FormMargin = old;
    }

    /// <summary>
    /// 弹出窗体的高
    /// </summary>
    public double FormHeight
    {
        get { return (double)GetValue(FormHeightProperty); }
        set { SetValue(FormHeightProperty, value); }
    }
    public static readonly DependencyProperty FormHeightProperty =
        DependencyProperty.Register("FormHeight", typeof(double), _classType, new PropertyMetadata(0.0, OnFormHeightChanged));
    private static void OnFormHeightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ctl = (UC_ChildForm)d;
        ctl.OnFormHeightChanged((double)e.NewValue);
    }
    private void OnFormHeightChanged(double height)
    {
        if (gridContent.Children.Count == 0) return;
        // 解决关闭按钮不随父窗口大小变化问题
        var old = FormMargin;
        var marginVeri = (this.ActualHeight - height) / 2;
        old.Top = marginVeri;
        old.Bottom = marginVeri;
        FormMargin = old;
    }

    /// <summary>
    /// 声明路由事件
    /// 参数:要注册的路由事件名称,路由事件的路由策略,事件处理程序的委托类型(可自定义),路由事件的所有者类型
    /// </summary>
    public static readonly RoutedEvent FormClosedEvent = EventManager.RegisterRoutedEvent("FormClosed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UC_ChildForm));
    /// <summary>
    /// 窗体关闭的路由事件
    /// </summary>
    public event RoutedEventHandler FormClosed
    {
        // 将路由事件添加路由事件处理程序
        add { AddHandler(FormClosedEvent, value); }
        // 从路由事件处理程序中移除路由事件
        remove { RemoveHandler(FormClosedEvent, value); }
    }
    public static readonly RoutedEvent FormClosingEvent = EventManager.RegisterRoutedEvent("FormClosing", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UC_ChildForm));
    /// <summary>
    /// 窗体正在关闭时的路由事件
    /// </summary>
    public event RoutedEventHandler FormClosing
    {
        add { AddHandler(FormClosingEvent, value); }
        remove { RemoveHandler(FormClosingEvent, value); }
    }

    public UC_ChildForm()
    {
        InitializeComponent();
        Visibility = Visibility.Hidden;
    }

    private void BtnContentClose_Click(object sender, RoutedEventArgs e)
    {
        e.RoutedEvent = FormClosingEvent;
        this.RaiseEvent(e);
    }
    private void Grid_Click(object sender, RoutedEventArgs e)
    {
        var ui = gridContent.Children[0];
        var value = InvokeGetProperty(ui, "FormData");
        FormCloseMethod(value);

        Hide();
        e.Handled = true;
    }
    /// <summary>
    /// 动态获取对象的属性值
    /// </summary>
    /// <param name="obj">指定的对象</param>
    /// <param name="propertyName">属性名称(字符串形式)</param>
    /// <param name="args">传递给属性用的参数</param>
    /// <returns></returns>
    private object InvokeGetProperty(object obj, string propertyName)
    {
        Type type = obj.GetType();
        var prop = type.GetProperty(propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        if (null != prop && prop.CanRead)
        {
            return prop.GetValue(obj, null);
        }
        return null;
    }
    private void FormCloseMethod(object value)
    {
        // 定义传递参数
        var args = new RoutedPropertyChangedEventArgs<object>(default, value, FormClosedEvent);
        // 引用自定义路由事件
        this.RaiseEvent(args);
    }

    public void Show(UIElement uIElement)
    {
        this.Visibility = Visibility.Visible;
        gridContentBackground.Visibility = Visibility.Visible;
        gridContent.Children.Clear();
        gridContent.Children.Add(uIElement);
    }
    public void Hide()
    {
        this.Visibility = Visibility.Hidden;
        gridContentBackground.Visibility = Visibility.Hidden;
        gridContent.Children.Clear();
        FormMargin = _defaultThickness;
        FormWidth = 0;
        FormHeight = 0;
    }

}

<Grid>
    <Grid>
        <!--主窗口-->
    </Grid> 
    <local:UC_ChildForm x:Name="ucChildDlg" FormClosed="UcChildDlg_FormClosed" FormClosing="UcChildDlg_FormClosing"/>
</Grid>
UC_UserControl2 ucInfo;
private void BtnDetails_Click(object sender, RoutedEventArgs e)
{
    ucInfo = new UC_UserControl2();
    ucChildDlg.Show(ucInfo);
    ucChildDlg.FormMargin = new Thickness(20,30,40,50);
    // ucChildDlg.FormWidth = 600;
    // ucChildDlg.FormHeight = 400;
}
private void UcChildDlg_FormClosing(object sender, RoutedEventArgs e)
{
    //  e.Handled = true;
}
private void UcChildDlg_FormClosed(object sender, RoutedEventArgs e)
{
    var args = (RoutedPropertyChangedEventArgs<object>)e;
    lbMsg.Text = args.NewValue?.ToString();
}

Prism弹框,兼容ChildForm

蒙版由Window窗口的主页面控制。
蒙版显隐可以由事件实现。
Prism弹框

Prism弹框,可设置子窗口大小,可切换

View XAML

<UserControl x:Class="XXX.PrismDialog"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"           
             prism:ViewModelLocator.AutoWireViewModel="True">
    <prism:Dialog.WindowStyle>
        <Style TargetType="Window">
            <Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterOwner" />
            <Setter Property="ShowInTaskbar" Value="False" />
            <Setter Property="SizeToContent" Value="WidthAndHeight" />
            <Setter Property="WindowStyle" Value="None" />
            <Setter Property="AllowsTransparency" Value="True" />
            <Setter Property="Background" Value="Transparent" />
        </Style>
    </prism:Dialog.WindowStyle>
    <Grid>
        <Border Background="{StaticResource RegionBrush}" BorderBrush="{StaticResource PanelBorderBrush}" BorderThickness="1" CornerRadius="4">
            <Grid Margin="0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" x:Name="row"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid Margin="0">
                    <TextBlock FontSize="16" Foreground="{DynamicResource ForegroundBrush80}" Text="{Binding Title}" Margin="20,0,0,8" VerticalAlignment="Bottom" />
                    <Button Width="12" Height="12" Margin="4,4,20,4" HorizontalAlignment="Right" BorderThickness="0" Command="{Binding CloseCommand}" Style="{StaticResource ButtonDefault}"
                            Visibility="{Binding CloseVisible, Converter={StaticResource Boolean2VisibilityConverter}}">
                        <Button.Background>
                            <ImageBrush ImageSource="{DynamicResource MessageDialogSource}" />
                        </Button.Background>
                    </Button>
                </Grid>
                <ContentControl Grid.Row="1" Margin="0,0,0,4" Width="{Binding DialogWidth}" Height="{Binding DialogHeight}" x:Name="contentControl"/>
            </Grid>
        </Border>
    </Grid>
</UserControl>

View CS

public partial class PrismDialog : UserControl
{
    public PrismDialog(IRegionManager regionManager)
    {
        InitializeComponent();
        var regionName = System.Guid.NewGuid().ToString();
        if (regionManager != null && !regionManager.Regions.ContainsRegionWithName(regionName))
        {
            SetRegionManager(regionManager, contentControl, regionName);
        }
        if (this.DataContext is PrismDialogViewModel vm)
        {
            vm.RegionName = regionName;
        }
    }
    private void SetRegionManager(IRegionManager regionManager, DependencyObject regionTarget, string regionName)
    {
        RegionManager.SetRegionName(regionTarget, regionName);
        RegionManager.SetRegionManager(regionTarget, regionManager);
    }
}

ViewModel

using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Linq;

public class PrismDialogViewModel : BindableBase, IDialogAware
{
    #region Fields

    private readonly IRegionManager _regionManager;
    private readonly IEventAggregator _eventAggregator;
    private readonly IDialogService _dialogService;
    private readonly IContainerExtension _container;

    /// <summary>
    /// 可否关闭弹框,默认true可以关闭
    /// </summary>
    private bool _bCanClosed;

    private readonly string _message;

    #endregion Fields

    #region Properties

    public string RegionName { get; set; }
    private string _tittle = "页面标题";

    /// <summary>
    /// 窗口的标题
    /// </summary>
    public string Title
    {
        get => _tittle;
        set => SetProperty(ref _tittle, value);
    }

    private double _dialogWidth;

    /// <summary>
    /// 弹出窗口的宽
    /// </summary>
    public double DialogWidth
    {
        get => _dialogWidth;
        set => SetProperty(ref _dialogWidth, value);
    }

    private double _dialogHeight;

    /// <summary>
    /// 弹出窗口的高
    /// </summary>
    public double DialogHeight
    {
        get => _dialogHeight;
        set => SetProperty(ref _dialogHeight, value);
    }

    private bool _closeVisible;

    /// <summary>
    /// 关闭按钮的可见性
    /// </summary>
    public bool CloseVisible
    {
        get => _closeVisible;
        set => SetProperty(ref _closeVisible, value);
    }

    #endregion Properties

    #region Commands

    public DelegateCommand CloseCommand => new DelegateCommand(ExecuteCloseCommand);

    #endregion Commands

    public PrismDialogViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IDialogService dialogService, IContainerExtension container)
    {
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
        _dialogService = dialogService;
        _container = container;
        eventAggregator.GetEvent<DialogCanCloseEvent>().Subscribe(DialogCanCloseEvent);
        eventAggregator.GetEvent<DialogCloseEvent>().Subscribe(DialogClosedEvent);
        DialogWidth = 1000;
        DialogHeight = 820;
        _bCanClosed = true;
        _message = "有新的操作未保存,是否关闭?";
    }

    #region Execute
    private void ExecuteCloseCommand()
    {
        Close(new DialogResult(ButtonResult.Ignore));
    }

    private void DialogCanCloseEvent(bool bClose)
    {
        _bCanClosed = bClose;
    }

    private void DialogClosedEvent(DialogParameters obj)
    {
        DialogResult result = new DialogResult(ButtonResult.Ignore, obj);
        Close(result);
    }

    private void Close(DialogResult result)
    {
        if (_bCanClosed)
        {
            _regionManager.Regions.Remove(RegionName);
            RequestClose?.Invoke(result);
        }
        else
        {
            _dialogService.ShowMessage("提示:", _message, System.Windows.Visibility.Visible, callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    return;
                }
                _regionManager.Regions.Remove(RegionName);
                RequestClose?.Invoke(result);
            });
        }
    }

    #endregion Execute

    #region Interface IDialogAware

    public event Action<IDialogResult> RequestClose;

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {
        _eventAggregator.GetEvent<DialogCanCloseEvent>().Unsubscribe(DialogCanCloseEvent);
        _eventAggregator.GetEvent<DialogCloseEvent>().Unsubscribe(DialogClosedEvent);
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        Title = parameters.GetValue<string>("title");
        DialogWidth = parameters.GetValue<double>("width");
        DialogHeight = parameters.GetValue<double>("height");
        CloseVisible = parameters.GetValue<bool>("close");
        var type = parameters.GetValue<Type>("type");
        var source = type.FullName;

        var region = _regionManager.Regions[RegionName];
        var view = region.Views.FirstOrDefault(x => x.GetType() == type);
        if (view == null)
        {
            view = _container.Resolve(type, source);
            region.Add(view);
        }
        region.Activate(view);

        var para = parameters.GetValue<NavigationParameters>("navigationParameters");
        _regionManager.RequestNavigate(RegionName, source, para);
    }

    #endregion Interface IDialogAware
}

Demo

containerRegistry.RegisterDialog<Views.PrismDialog>();

IDialogResult dialogResult = null;
var param = new NavigationParameters();
_dependencyService.ShowDialog(typeof(Views.DemoEdit), param, 600, 300, "页面标题", bVisible: true, callback: result => { dialogResult = result; });

Prism弹框,Adorner蒙版,不可切换

View XAML

<UserControl x:Class="XXX.PrismDialog2"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <prism:Dialog.WindowStyle>
        <Style TargetType="Window">
            <Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterOwner" />
            <Setter Property="ShowInTaskbar" Value="False" />
            <Setter Property="SizeToContent" Value="WidthAndHeight" />
            <Setter Property="WindowStyle" Value="None" />
            <Setter Property="AllowsTransparency" Value="True" />
            <Setter Property="Background" Value="Transparent" />
        </Style>
    </prism:Dialog.WindowStyle>
    <Grid>
        <Border Background="{StaticResource RegionBrush}" BorderBrush="{StaticResource PanelBorderBrush}" BorderThickness="1" CornerRadius="4">
            <Grid Margin="0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" x:Name="row"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid Margin="0">
                    <TextBlock FontSize="16" Foreground="{DynamicResource ForegroundBrush80}" Text="{Binding Title}" Margin="20,0,0,8" VerticalAlignment="Bottom" />
                    <Button Width="12" Height="12" Margin="4,4,20,4" HorizontalAlignment="Right" BorderThickness="0" Command="{Binding CloseCommand}" Style="{StaticResource ButtonDefault}"
                            Visibility="{Binding CloseVisible, Converter={StaticResource Boolean2VisibilityConverter}}">
                        <Button.Background>
                            <ImageBrush ImageSource="{DynamicResource MessageDialogSource}" />
                        </Button.Background>
                    </Button>
                </Grid>
                <ContentControl Grid.Row="1" Margin="0,0,0,4" x:Name="contentControl"/>
            </Grid>
        </Border>
    </Grid>
</UserControl>


View CS

using HandyControl.Tools;
using Microsoft.Xaml.Behaviors.Layout;
using Prism.Regions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

public partial class PrismDialog2 : UserControl
{
    private AdornerContainer _adornerContainer;

    public PrismDialog2(IRegionManager regionManager)
    {
        InitializeComponent();

        string regionName = System.Guid.NewGuid().ToString();
        if (regionManager != null && !regionManager.Regions.ContainsRegionWithName(regionName))
        {
            SetRegionManager(regionManager, contentControl, regionName);
        }
        if (DataContext is PrismDialog2ViewModel vm)
        {
            vm.RegionName = regionName;
            vm.CloseMaskEvent += Vm_CloseMaskEvent;
        }

        ShowMask();
    }

    private void Vm_CloseMaskEvent(object sender, System.EventArgs e)
    {
        HideMask();
    }

    private void ShowMask()
    {
        Window activeWidow = WindowHelper.GetActiveWindow();
        AdornerDecorator decorator = VisualHelper.GetChild<AdornerDecorator>(activeWidow);
        if (decorator != null)
        {
            AdornerLayer layer = decorator.AdornerLayer;
            if (layer != null && _adornerContainer == null)
            {
                _adornerContainer = new AdornerContainer(layer);
                Grid mask = new Grid
                {
                    Background = new SolidColorBrush(Colors.Gray),
                    Opacity = 0.8
                };
                _adornerContainer.Child = mask;
                layer.Add(_adornerContainer);
                layer.Visibility = Visibility.Visible;
            }
        }
    }

    private void HideMask()
    {
        Window activeWidow = WindowHelper.GetActiveWindow();
        AdornerDecorator decorator = VisualHelper.GetChild<AdornerDecorator>(activeWidow);
        if (decorator != null)
        {
            AdornerLayer layer = decorator.AdornerLayer;
            _adornerContainer.Child = null;
            layer.Remove(_adornerContainer);
            _adornerContainer = null;
            layer.Visibility = Visibility.Hidden;
        }
    }

    private void SetRegionManager(IRegionManager regionManager, DependencyObject regionTarget, string regionName)
    {
        RegionManager.SetRegionName(regionTarget, regionName);
        RegionManager.SetRegionManager(regionTarget, regionManager);
    }
}

ViewModel

using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Linq;

public class PrismDialog2ViewModel : BindableBase, IDialogAware
{
    #region Fields

    private readonly IRegionManager _regionManager;
    private readonly IEventAggregator _eventAggregator;
    private readonly IDialogService _dialogService;
    private readonly IContainerExtension _container;

    /// <summary>
    /// 可否关闭弹框,默认true可以关闭
    /// </summary>
    private bool _bCanClosed;

    private readonly string _message;

    #endregion Fields

    #region Properties

    public string RegionName { get; set; }
    private string _tittle = "页面标题";

    /// <summary>
    /// 页面标题
    /// </summary>
    public string Title
    {
        get => _tittle;
        set => SetProperty(ref _tittle, value);
    }

    private bool _closeVisible;

    /// <summary>
    /// 关闭按钮的可见性
    /// </summary>
    public bool CloseVisible
    {
        get => _closeVisible;
        set => SetProperty(ref _closeVisible, value);
    }

    #endregion Properties

    #region Commands

    /// <summary>
    /// 关闭蒙版事件
    /// </summary>
    public event EventHandler CloseMaskEvent;

    public DelegateCommand CloseCommand => new DelegateCommand(ExecuteCloseCommand);

    #endregion Commands

    public PrismDialog2ViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IDialogService dialogService, IContainerExtension container)
    {
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
        _dialogService = dialogService;
        _container = container;
        _eventAggregator.GetEvent<DialogCanCloseEvent>().Subscribe(DialogCanCloseEvent);
        _eventAggregator.GetEvent<DialogCloseEvent>().Subscribe(DialogClosedEvent);
        _bCanClosed = true;
        _message = "有新的操作未保存,是否关闭?";
    }

    #region Execute

    private void ExecuteCloseCommand()
    {
        Close(new DialogResult(ButtonResult.Ignore));
    }

    private void DialogCanCloseEvent(bool bClose)
    {
        _bCanClosed = bClose;
    }

    private void DialogClosedEvent(DialogParameters obj)
    {
        DialogResult result = new DialogResult(ButtonResult.Ignore, obj);
        Close(result);
    }

    private void Close(DialogResult result)
    {
        if (_bCanClosed)
        {
            _regionManager.Regions.Remove(RegionName);
            RequestClose?.Invoke(result);
            CloseMaskEvent?.Invoke(this, EventArgs.Empty);
        }
        else
        {
            _dialogService.ShowMessage("提示:", _message, System.Windows.Visibility.Visible, callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    return;
                }
                _regionManager.Regions.Remove(RegionName);
                RequestClose?.Invoke(result);
            });
        }
    }

    #endregion Execute

    #region Interface IDialogAware

    public event Action<IDialogResult> RequestClose;

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {
        _eventAggregator.GetEvent<DialogCanCloseEvent>().Unsubscribe(DialogCanCloseEvent);
        _eventAggregator.GetEvent<DialogCloseEvent>().Unsubscribe(DialogClosedEvent);
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        Title = parameters.GetValue<string>("title");
        CloseVisible = parameters.GetValue<bool>("close");
        var type = parameters.GetValue<Type>("type");
        var source = type.FullName;

        var region = _regionManager.Regions[RegionName];
        var view = region.Views.FirstOrDefault(x => x.GetType() == type);
        if (view == null)
        {
            view = _container.Resolve(type, source);
            region.Add(view);
        }
        region.Activate(view);

        var para = parameters.GetValue<NavigationParameters>("navigationParameters");
        _regionManager.RequestNavigate(RegionName, source, para);
    }

    #endregion Interface IDialogAware
}

Demo

containerRegistry.RegisterDialog<Views.PrismDialog2>();

var param = new Prism.Regions.NavigationParameters();
_dependencyService.ShowDialog(typeof(Views.DemoEdit), param, "页面标题", callback: (rslt) =>
{
     if (rslt != null && rslt.Parameters != null) // 页面关闭后
     {
          // TODO
     }
});

// 子窗口
_dependencyService.DialogClose(new Prism.Services.Dialogs.DialogParameters());
posted @ 2020-03-19 16:10  wesson2019  阅读(1485)  评论(0编辑  收藏  举报