4
4

More than 1 year has passed since last update.

WinUI3 Desktopでダークモードに対応する (Windows App SDK)

Last updated at Posted at 2021-11-21

WinUI3はダークモードに標準で対応している、ことになっています。

Windowsの設定でアプリのダークモードを有効にすると…。

p1.png

なんということでしょう。タイトルバーだけ、ダークではありません。

各UI要素にはRequestedThemeというプロパティがあり、動的にテーマを設定できます。しかしこれはWindowには適用されません。

タイトルバーにもWindowsのテーマを適用するには、タイトルバーを非表示にして、自前のタイトルバーをXAMLで作ります。

MainWindow.xaml
<Window
    x:Class="Sample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    >

    <Grid Grid.RowDefinitions="Auto,*">
        <StackPanel Grid.Row="0" Height="35" Orientation="Horizontal" Spacing="15" x:Name="TitleBar" HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <TextBlock VerticalAlignment="Center" Text="MyApp" />
        </StackPanel>
        <NavigationView
            Grid.Row="1"
            SelectionChanged="NavigationView_SelectionChanged"
            Loaded="NavigationView_Loaded">
            <NavigationView.MenuItems>
                <NavigationViewItem Content="Menu Item1" Tag="SamplePage1" x:Name="SamplePage1Item" >
                    <NavigationViewItem.Icon>
                        <SymbolIcon Symbol="Play"/>
                    </NavigationViewItem.Icon>
                </NavigationViewItem>
            </NavigationView.MenuItems>
            <Frame x:Name="contentFrame"/>
        </NavigationView>
    </Grid>
</Window>

Grid.Row="0"がタイトルバーです。このサンプルにはアプリのアイコンがありません。アプリのアイコンを付けたい人は、TextBlockの前にImageを置いてください。

MainWindow.cs
public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        ExtendsContentIntoTitleBar = true;
        SetTitleBar(TitleBar);
    }
}

そしてコード側で、元のタイトルバーを無効にして、XAMLで作ったタイトルバーに差し替えます。

p2.png

これでタイトルバーにもテーマが適用されるようになりました。

4
4
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
4