Material Design in XAML 如何理解 DialogHost


首先,本文假設您已經使用 MDIX 設置了一個項目。此外,它推測您了解模型-視圖-視圖模型 (MVVM) 模式。但是,DialogHost也可以在沒有 MVVM 的情況下使用。

小試牛刀DialogHost

Dialog是Material Design In XAML中非常重要且強大的一個控件,首先我們從一個簡單的例子開始。

<Window x:Class="MaterilDesign.MainWindow"
        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:MaterilDesign" 
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>

    <materialDesign:DialogHost CloseOnClickAway="True">
        <materialDesign:DialogHost.DialogContent>
            <Grid Margin="16">
                <TextBlock Text="我的第一個DialogHost" FontSize="20"/>
            </Grid>
        </materialDesign:DialogHost.DialogContent>

        <Button Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}" Width="160" Content="打開" Margin="0,64,0,0"/>
    </materialDesign:DialogHost>
</Window>

然后在App.Xaml中加入Material Design的默認樣式,並添加主題顏色,這里不明白為什么這么寫的話,可以去看一下官方文檔,或者等待后續文章的更新。

<Application x:Class="MaterilDesign.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:MaterilDesign" 
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <materialDesign:BundledTheme BaseTheme="Inherit"  PrimaryColor="Blue"  SecondaryColor="Lime"
                                             ColorAdjustment="{materialDesign:ColorAdjustment}" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

上邊的代碼運行起來就是下邊這樣一個非常簡單的對話框了。

DialogHost 由三個單獨的 UI 組件組成:宿主控件、覆蓋層和對話框。宿主控件包含應將對話框放在其上的內容。通常,它放置在 XAML 的根目錄附近,以便它涵蓋所有內容。疊加層是覆蓋主機控件內所有內容的變暗區域。最后,對話框本身包含要顯示的內容。默認情況下,對話框顯示在彈出窗口內部。由於彈出窗口是一個單獨的窗口,因此對話框可以大於其父窗口。如果要將對話框限制到其父窗口,則可以將靜態資源樣式 MaterialDesignEmbeddedDialogHost 應用於 DialogHost。

 顯示和關閉對話框

DialogHost 適用於同時使用 MVVM 和Winform風格的應用程序。因此,有幾種方法可以顯示對話框。你可以選擇在應用中使用這些選項中的任意一種。

(1)使用路由命令

DialogHost提供了兩個用於顯示和隱藏對話框的路由命令;OpenDialogCommand 和 CloseDialogCommand。這是最簡單的純 XAML 選項,因為它只是在元素樹上向上移動,直到遇到 DialogHost 控件。將其設置為 Command 屬性,它將顯示對話框。下邊是打開和關閉的命令。

<Button Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}"/>
<Button Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}"/>

(2)綁定DialogHost的IsOpen 屬性

為了對對話框的狀態進行簡單的編程控制,DialogHost 提供了一個 IsOpen 屬性。切換此屬性的狀態可以控制對話框顯示或隱藏。屬性還可以與數據綁定配對,使其易於在 MVVM 體系結構中使用。下邊代碼涉及到使用Mvvm框架Prism,使用前需要首先安裝Prism.Wpf

<materialDesign:DialogHost IsOpen="{Binding IsDialogOpen}">
    <materialDesign:DialogHost.DialogContent>
        <Grid Margin="16">
            <TextBlock Text="我的第一個DialogHost" FontSize="20"/>
        </Grid>
    </materialDesign:DialogHost.DialogContent>
    <Button Command="{Binding ShowDialogCommand}" Width="160" Content="打開" Margin="0,64,0,0"/>
</materialDesign:DialogHost>
using Prism.Commands;
using Prism.Mvvm;

namespace MaterilDesign
{
    public class MainWindowViewModel : BindableBase
    {
        private bool _IsDialogOpen;
        public bool IsDialogOpen
        {
            get => _IsDialogOpen;
            set => SetProperty(ref _IsDialogOpen, value);
        }

        public DelegateCommand ShowDialogCommand => new(OnShowDialog);

        public MainWindowViewModel(){}

        private void OnShowDialog()
        {
            IsDialogOpen = true;
        }
    }
}

或者直接在按鈕的點擊事件中編寫DialogHost.IsOpen = true;的代碼,需要在xaml中定義控件的Name為DialogHost。也可以同樣達到打開對話框的效果。

(3)關閉對話框

若要使對話框在用戶單擊疊加層時自動關閉,請將 CloseOnClickAway 屬性設置為“True”。

<materialDesign:DialogHost CloseOnClickAway="True">

   ...

</materialDesign:DialogHost>

以上打開關閉對話框的方法都需要在Xaml中首先創建DialogHost對象,下邊說明如何通過代碼動態創建打開和關閉DialogHost

(4)動態創建對話框。

為了更好地控制對話框,DialogHost 類上有幾個靜態的 Show 方法。所有這些方法都返回 Tasks,並應用作異步方法。對話框的內容在 XAML 中指定,然后在前面的示例中顯示或隱藏。使用 Show 方法時,必須傳遞對話框的內容。這允許創建動態對話框。

var dialogContent = new TextBlock
{
   Text = "動態對話框!",
   Margin = new Thickness(20)
};
await MaterialDesignThemes.Wpf.DialogHost.Show(dialogContent);

通過上邊這種方法也可以打開一個對話框,但是如果需要在代碼中創建對話框UI。更好的辦法是為對話框的UI創建一個數據模板,並將數據對象作為對話框的內容傳遞,在數據模板中綁定數據。

<Window x:Class="MaterilDesign.MainWindow"
        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:MaterilDesign" 
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>

    <materialDesign:DialogHost CloseOnClickAway="True">
        <Button Command="{Binding ShowDialogCommand}" Width="160" Content="打開" Margin="0,64,0,0"/>
        <materialDesign:DialogHost.DialogContentTemplate>
            <DataTemplate DataType="local:Person">
                <StackPanel Margin="20">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text="{Binding Age}" />
                </StackPanel>
            </DataTemplate>
        </materialDesign:DialogHost.DialogContentTemplate>
    </materialDesign:DialogHost>
    
</Window>
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;

namespace MaterilDesign
{
    public class MainWindowViewModel : BindableBase
    {
        public DelegateCommand ShowDialogCommand => new(OnShowDialog);

        public MainWindowViewModel(){}

        private async void OnShowDialog()
        {
            var person = new Person
            {
                Name = "測試",
                Age = 12,
            };
            await DialogHost.Show(person);
        }
    }

    public class Person
    {
        public string? Name { get; set; }
        public int? Age { get; set; }
    }
}

Show 方法還包括在打開或關閉對話框時調用的回調委托的重載。您還可以直接在 DialogHost 上注冊 DialogOpen 和 DialogClosed 事件。這些回調的事件參數包含一個 DialogSession 對象。此會話對象可以更新已顯示的對話的內容或關閉可見對話框。

using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;

namespace MaterilDesign
{
    public class MainWindowViewModel : BindableBase
    {
        private DialogSession? _dialogOpeneSession;

        public DelegateCommand ShowDialogCommand => new(OnShowDialog);

        public MainWindowViewModel(){}

        private async void OnShowDialog()
        {
            var person = new Person
            {
                Name = "測試",
                Age = 12,
            };
            await DialogHost.Show(person, new DialogOpenedEventHandler((object sender, DialogOpenedEventArgs args) =>
             {
                 // 將Session賦值給私有字段,方便其他方法對內容進行更行操作
                 _dialogOpeneSession = args.Session;
                 var newPerson = new Person
                 {
                     Name = "張三",
                     Age = 12,
                 };

                 // 更新Session內容
                 _dialogOpeneSession.UpdateContent(newPerson);

                 //關閉對話框,將_dialogOpeneSession置為null,避免錯誤應用
                 _dialogOpeneSession.Close();
                 _dialogOpeneSession = null;
             }),new DialogClosingEventHandler((object sender,DialogClosingEventArgs args) =>
             {
                 // 獲取Session中的內容,將結果推送到有需要的地方,獲取返回值的一種方法
                 // 關閉事件
             }));
        }
    }

    public class Person
    {
        public string? Name { get; set; }
        public int? Age { get; set; }
    }
}

最后,還有用於傳遞對話標識符的其他重載。如果只有一個 DialogHost 實例,則 Show 方法將自動使用它。但是,在具有多個 DialogHost 實例的情況下,必須指定一個對話框標識符。此唯一 ID 標識要使用的對話框主機控件。

<materialDesign:DialogHost Identifier="MyDialogHost">
...
</materialDesign:DialogHost>
await MaterialDesignThemes.Wpf.DialogHost.Show(person, "MyDialogHost");

(5)返回值

使用靜態 Show 方法顯示的對話框也可以返回結果值。這些結果值可以是所需的對象。

object result = await MaterialDesignThemes.Wpf.DialogHost.Show(...);
//處理返回的結果值

根據對話框的關閉方式,有幾種方法可以指定返回值。

  • 如果使用對話框關閉命令,請在使用該命令的同一元素上設置 CommandParameter。
  • 如果使用 CloseOnClickAway,請在 DialogHost 上設置 CloseOnClickAwayParameter。
  • 如果使用對話框會話,請將參數傳遞給 Close 方法。
  • 屬性不支持傳遞結果。必須使用其他方法之一。

盡管 XAML 對話主機是 MDIX 庫中最強大的控件之一,但它也是最容易被誤解的控件之一。但是,只需稍加努力,它就可以使在應用程序中使用“模式”對話框變得輕而易舉。它可以改善用戶界面的美感並簡化用戶體驗。

 

下一篇將說明在實際生產中DialogHost遇到的兩個問題及解決方案。

 

聲明,本文在Material Design in XAML – How to Make Sense of the DialogHost基礎之上進行了擴展撰寫。

涉及使用軟件框架版本如下:

Mvvm框架 Prism8+

UI框架MaterialDesignThemes4.4.0

Net版本 5.0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM