single.php

C# WinUI3でウィンドウの背景色を取得する方法

C# WinUI 3アプリを作っていく途中で、調べたことを忘録的に投稿します。今回はWinUI3プロジェクトでウィンドウの背景色[BackgroundBrush]を取得する方法です。

アプリケーションのリソースから取得

結論から書くと[Application.Resources]プロパティから取得できました。

[新しい項目の追加]画面で[WinUI3|空白のページ(WinUI3)]で作成されるXaml内の[Background]プロパティに設定があります。

<?xml version="1.0" encoding="utf-8"?>
<Page
  x:Class="WinUi3Samples.ContentPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:WinUi3Samples"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="d"
  Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

  <Grid>
  </Grid>
</Page>

テーマとダークカラーが導入されて若干面倒な作りになっていますが、このリソースを呼び出すと画面(ページ)の背景色が取得できます。

ブラシが取得されるので、こんな感じで色(Windows.UI.Color)に変換します。

SolidColorBrush? themebrush = Application.Current.Resources["ApplicationPageBackgroundThemeBrush"] as SolidColorBrush;
if(themebrush != null)
{
  Windows.UI.Color themecolor = themebrush.Color;
}

Windowsの[個人用設定|色|モードを選ぶ]の設定で異なりますが、実行すると次のような色情報が取得されます。

//ダークの場合
themecolor = {#FF202020} 

//ライトの場合
themecolor = {#FFF3F3F3} 

まとめ

今回は、WinUI3プロジェクトでウィンドウの背景色[BackgroundBrush]を取得する方法を紹介しました。

[”ApplicationPageBackgroundThemeBrush”]をキーにしてリソースから背景色の色情報が取得できます。

WinUI 3でウィンドウの背景色を取得したい人の参考になれば幸いです。

スポンサーリンク

最後までご覧いただき、ありがとうございます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です