4
3

More than 1 year has passed since last update.

Windows App SDK, WinUI3, Desktopでダイアログボックスを表示する

Last updated at Posted at 2021-11-14

この記事はWindows App SDK Preview 3をベースにしています。

p5.png

こいつを表示するのが今回の目標です。これまでのWPF/Windows Forms/Win32 APIではMessageBoxを使っていました。しかしWinUI3 Desktopでは基本的にこれらは使えません(使えなくはありませんが、WinUI3である意味が…)。

WinUI3 DesktopではUWPと同じようにMessageDialogまたはContentDialogを使います。

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
        Handle = this;
    }

    public static MainWindow Handle { get; private set; }
}

MainWindowのインスタンスをゲットできるようにしておいて…。

using Microsoft.UI.Xaml.Controls;
using MvvmGen;

[ViewModel]
public partial class SamplePage1ViewModel
{
    [Command]
    private async void SampleButton()
    {
        var cd = new ContentDialog
        {
            Title = "Sample Application",
            Content = "Hello World!",
            CloseButtonText = "OK"
        };

        cd.XamlRoot = MainWindow.Handle.Content.XamlRoot;
        await cd.ShowAsync();
    }
}

ContentDialogを生成してダイアログを表示します。

XamlRootにMainWindowのXamlRootを指定しているところが肝になります。desktopではこれがないとSystem.Runtime.InteropServices.COMExceptionの例外が発生してしまいます。これはいずれ解消されるバグだと思いますが…。

<Button Content="Fire!" Command="{Binding SampleButtonCommand}"/>

そしてもちろん、XAMLでボタンを設置して、SampleButtonにbindします。

コマンドの実装にはMvvmGenを使用しています。MvvmGenを使わなくてもダイアログの表示はできます。[ViewModel]属性、[Command]属性についての詳細は以下の記事を参照してください。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3