Skip to content

Commit

Permalink
现在 Demo 可以根据设置的颜色更改主题了
Browse files Browse the repository at this point in the history
  • Loading branch information
wherewhere committed Jul 1, 2024
1 parent 513bc37 commit 01c8a50
Show file tree
Hide file tree
Showing 11 changed files with 197 additions and 88 deletions.
26 changes: 20 additions & 6 deletions .github/workflows/build-and-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,26 @@ jobs:
env:
Solution_Name: MicaForUWP.sln
Project_Directory: MicaDemo
Signing_Certificate: MicaDemo_TemporaryKey.pfx

steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0

# Decode the base 64 encoded pfx and save the Signing_Certificate
- name: Decode the pfx
run: |
$pfx_cert_byte = [System.Convert]::FromBase64String("${{ secrets.Base64_Encoded_Pfx }}")
$certificatePath = Join-Path -Path $env:Project_Directory -ChildPath MicaDemo_TemporaryKey.pfx
$pfx_cert_byte = [System.Convert]::FromBase64String("$env:Certificate")
$certificatePath = Join-Path -Path $env:Project_Directory -ChildPath $env:Signing_Certificate
[IO.File]::WriteAllBytes("$certificatePath", $pfx_cert_byte)
env:
Certificate: ${{ secrets.Base64_Encoded_Pfx }}

# Add MSBuild to the PATH: https://github.com/microsoft/setup-msbuild
- name: Setup MSBuild.exe
uses: microsoft/setup-msbuild@v1
uses: microsoft/setup-msbuild@v2
with:
msbuild-architecture: x64

Expand All @@ -45,18 +48,29 @@ jobs:

# Create the app package by building and packaging the Windows Application Packaging project
- name: Create the app package
run: msbuild $env:Solution_Name /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageDir="$env:Appx_Package_Dir" /p:AppxPackageSigningEnabled=true /p:PackageCertificateThumbprint="0CDF4A03E9BE9DD789894BB3C7AD3DEDECD9AB25" /p:PackageCertificateKeyFile=MicaDemo_TemporaryKey.pfx /p:PackageCertificatePassword="$env:Password"
run: msbuild $env:Solution_Name `
/p:LangVersion=latest `
/p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" `
/p:Configuration=$env:Configuration `
/p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode `
/p:AppxBundle=$env:Appx_Bundle `
/p:AppxPackageDir="$env:Appx_Package_Dir" `
/p:AppxPackageSigningEnabled=true `
/p:PackageCertificateThumbprint="$env:Thumbprint" `
/p:PackageCertificateKeyFile=$env:Signing_Certificate `
/p:PackageCertificatePassword="$env:Password"
env:
Appx_Bundle: Always
Appx_Bundle_Platforms: x86|x64|ARM
Appx_Package_Build_Mode: SideloadOnly
Appx_Package_Dir: AppxPackages\
Configuration: Release
Thumbprint: 0CDF4A03E9BE9DD789894BB3C7AD3DEDECD9AB25
Password: ${{ secrets.Password }}

# Upload the MSIX package: https://github.com/marketplace/actions/upload-a-build-artifact
- name: Upload build artifacts
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: MSIX Package
path: MicaDemo/AppxPackages/**
27 changes: 13 additions & 14 deletions MicaDemo/Helpers/ThemeHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using MicaDemo.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
Expand Down Expand Up @@ -31,7 +32,7 @@ public static event Action<bool> UISettingChanged
remove => actions.Remove(value);
}

public static void InvokeUISettingChanged(bool value) => actions.Invoke(value);
private static void InvokeUISettingChanged(bool value) => actions.Invoke(value);

#endregion

Expand Down Expand Up @@ -65,9 +66,9 @@ await Task.WhenAll(WindowHelper.ActiveWindows.Values.Select(async window =>
rootElement.RequestedTheme = value;
}
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out System.Collections.Generic.Dictionary<UIElement, AppWindow> appWindows))
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out HashSet<AppWindow> appWindows))
{
foreach (FrameworkElement element in appWindows.Keys.OfType<FrameworkElement>())
foreach (FrameworkElement element in appWindows.Select(x => x.GetXamlRootForWindow()).OfType<FrameworkElement>())
{
element.RequestedTheme = value;
}
Expand All @@ -88,21 +89,19 @@ static ThemeHelper()

public static async void Initialize(Window window)
{
if (window == null) { return; }
// Save reference as this might be null when the user is in another app
CurrentApplicationWindow = CurrentApplicationWindow ?? window;
if (CurrentApplicationWindow == null)
{ CurrentApplicationWindow = window; }
if (window?.Content is FrameworkElement rootElement)
{
rootElement.RequestedTheme = await GetRootThemeAsync(CurrentApplicationWindow);
}
{ rootElement.RequestedTheme = await GetRootThemeAsync(CurrentApplicationWindow); }
UpdateSystemCaptionButtonColors(window);
}

public static async void Initialize(AppWindow window)
{
if (window?.GetXamlRootForWindow() is FrameworkElement rootElement)
{
rootElement.RequestedTheme = await GetRootThemeAsync(CurrentApplicationWindow);
}
{ rootElement.RequestedTheme = await GetRootThemeAsync(CurrentApplicationWindow); }
UpdateSystemCaptionButtonColors(window);
}

Expand Down Expand Up @@ -145,9 +144,9 @@ public static void UpdateExtendViewIntoTitleBar(bool IsExtendsTitleBar)
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = IsExtendsTitleBar;
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out System.Collections.Generic.Dictionary<UIElement, AppWindow> appWindows))
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out HashSet<AppWindow> appWindows))
{
foreach (AppWindow appWindow in appWindows.Values)
foreach (AppWindow appWindow in appWindows)
{
appWindow.TitleBar.ExtendsContentIntoTitleBar = IsExtendsTitleBar;
}
Expand Down Expand Up @@ -183,9 +182,9 @@ public static async void UpdateSystemCaptionButtonColors()
TitleBar.ButtonBackgroundColor = TitleBar.ButtonInactiveBackgroundColor = ExtendViewIntoTitleBar ? Colors.Transparent : BackgroundColor;
}
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out System.Collections.Generic.Dictionary<UIElement, AppWindow> appWindows))
if (WindowHelper.IsAppWindowSupported && WindowHelper.ActiveAppWindows.TryGetValue(window.Dispatcher, out HashSet<AppWindow> appWindows))
{
foreach (AppWindow appWindow in appWindows.Values)
foreach (AppWindow appWindow in appWindows)
{
bool ExtendViewIntoTitleBar = appWindow.TitleBar.ExtendsContentIntoTitleBar;
AppWindowTitleBar TitleBar = appWindow.TitleBar;
Expand Down
55 changes: 54 additions & 1 deletion MicaDemo/Helpers/UIElementHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static class UIElementHelper
/// <summary>
/// Gets the flyout associated with this element.
/// </summary>
/// <param name="element">The flyout associated with this element.</param>
/// <param name="element">The element from which to read the property value.</param>
/// <returns>The flyout associated with this element, if any; otherwise, <see langword="null"/>. The default is <see langword="null"/>.</returns>
public static FlyoutBase GetContextFlyout(UIElement element)
{
Expand Down Expand Up @@ -165,5 +165,58 @@ private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedE
}

#endregion

#region BackgroundTransition

/// <summary>
/// Gets an instance of BrushTransition to automatically animate changes to the Background property.
/// </summary>
/// <param name="element">The element from which to read the property value.</param>
/// <returns>An instance of BrushTransition to automatically animate changes to the Background; otherwise, <see langword="null"/>. The default is <see langword="null"/>.</returns>
public static bool GetBackgroundTransition(UIElement element)
{
return (bool)element.GetValue(BackgroundTransitionProperty);
}

/// <summary>
/// Sets an instance of BrushTransition to automatically animate changes to the Background property.
/// </summary>
/// <param name="element">The element on which to set the attached property.</param>
/// <param name="value">The instance of BrushTransition to automatically animate changes to the Background property.</param>
public static void SetBackgroundTransition(UIElement element, bool value)
{
element.SetValue(BackgroundTransitionProperty, value);
}

/// <summary>
/// Identifies the BackgroundTransition dependency property.
/// </summary>
public static readonly DependencyProperty BackgroundTransitionProperty =
DependencyProperty.RegisterAttached(
"BackgroundTransition",
typeof(bool),
typeof(UIElementHelper),
new PropertyMetadata(false, OnBackgroundTransitionChanged));

private static void OnBackgroundTransitionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (ApiInformation.IsTypePresent("Windows.UI.Xaml.BrushTransition"))
{
switch (d)
{
case Panel panel:
panel.BackgroundTransition = e.NewValue is true ? new BrushTransition() : null;
break;
case Border border:
border.BackgroundTransition = e.NewValue is true ? new BrushTransition() : null;
break;
case ContentPresenter contentPresenter:
contentPresenter.BackgroundTransition = e.NewValue is true ? new BrushTransition() : null;
break;
}
}
}

#endregion
}
}
29 changes: 8 additions & 21 deletions MicaDemo/Helpers/WindowHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,44 +61,31 @@ public static void TrackWindow(this Window window)
}
}

public static void TrackWindow(this AppWindow window, Frame frame)
private static void TrackWindow(this AppWindow window, Frame frame)
{
if (!ActiveAppWindows.ContainsKey(frame.Dispatcher))
{
ActiveAppWindows[frame.Dispatcher] = new Dictionary<UIElement, AppWindow>();
ActiveAppWindows[frame.Dispatcher] = new HashSet<AppWindow>();
}

if (!ActiveAppWindows[frame.Dispatcher].ContainsKey(frame))
if (!ActiveAppWindows[frame.Dispatcher].Contains(window))
{
window.Closed += (sender, args) =>
{
if (ActiveAppWindows.TryGetValue(frame.Dispatcher, out Dictionary<UIElement, AppWindow> windows))
if (ActiveAppWindows.TryGetValue(frame.Dispatcher, out HashSet<AppWindow> windows))
{
windows?.Remove(frame);
windows?.Remove(window);
}
frame.Content = null;
window = null;
};
ActiveAppWindows[frame.Dispatcher][frame] = window;
ActiveAppWindows[frame.Dispatcher].Add(window);
}
}

public static UIElement GetXamlRootForWindow(this AppWindow window)
{
foreach (Dictionary<UIElement, AppWindow> windows in ActiveAppWindows.Values)
{
foreach (KeyValuePair<UIElement, AppWindow> element in windows)
{
if (element.Value == window)
{
return element.Key;
}
}
}
return null;
}
public static UIElement GetXamlRootForWindow(this AppWindow window) => ElementCompositionPreview.GetAppWindowContent(window);

public static Dictionary<CoreDispatcher, Window> ActiveWindows { get; } = new Dictionary<CoreDispatcher, Window>();
public static Dictionary<CoreDispatcher, Dictionary<UIElement, AppWindow>> ActiveAppWindows { get; } = IsAppWindowSupported ? new Dictionary<CoreDispatcher, Dictionary<UIElement, AppWindow>>() : null;
public static Dictionary<CoreDispatcher, HashSet<AppWindow>> ActiveAppWindows { get; } = IsAppWindowSupported ? new Dictionary<CoreDispatcher, HashSet<AppWindow>>() : null;
}
}
13 changes: 8 additions & 5 deletions MicaDemo/Pages/BlurPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
xmlns:helpers="using:MicaDemo.Helpers"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:media="using:MicaForUWP.Media"
Loaded="Page_Loaded"
NavigationCacheMode="Enabled"
mc:Ignorable="d">
<Page.Background>
Expand All @@ -20,20 +21,22 @@
</Grid.ChildrenTransitions>
<Grid.Background>
<media:BackdropBlurBrush
x:Name="BackdropBlurBrush"
AlwaysUseFallback="{Binding IsChecked, ElementName=AlwaysUseFallback, Mode=OneWay}"
Amount="{x:Bind Amount.Value, Mode=OneWay}"
BackgroundSource="{Binding SelectedValue, ElementName=BackgroundSource, Mode=OneWay}"
FallbackColor="{StaticResource SolidBackgroundFillColorBase}"
FallbackColor="{Binding TintColor, RelativeSource={RelativeSource Mode=Self}}"
TintColor="{x:Bind TintColor.Color, Mode=OneWay}"
TintOpacity="{x:Bind TintOpacity.Value, Mode=OneWay}" />
</Grid.Background>
<Border
Margin="{x:Bind ScrollViewerMargin}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{StaticResource CardBackgroundFillColorDefaultBrush}"
BorderBrush="{StaticResource CardBorderBrush}"
BorderThickness="{StaticResource CardBorderThickness}"
helpers:UIElementHelper.BackgroundTransition="True"
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
BorderBrush="{ThemeResource CardBorderBrush}"
BorderThickness="{ThemeResource CardBorderThickness}"
CornerRadius="8">
<Grid>
<Grid.RowDefinitions>
Expand Down Expand Up @@ -69,8 +72,8 @@
<MenuFlyout>
<MenuFlyoutItem
Click="Button_Click"
Tag="NewAppWindow"
IsEnabled="{x:Bind IsAppWindowSupported}"
Tag="NewAppWindow"
Text="Open New App Window">
<helpers:UIElementHelper.Icon>
<FontIcon FontFamily="{StaticResource SymbolThemeFontFamily}" Glyph="&#xE78B;" />
Expand Down
38 changes: 29 additions & 9 deletions MicaDemo/Pages/BlurPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using MicaForUWP.Media;
using System;
using Windows.ApplicationModel.Core;
using Windows.Foundation.Metadata;
using Windows.UI;
using Windows.UI.WindowManagement;
using Windows.UI.Xaml;
Expand All @@ -23,31 +22,52 @@ public sealed partial class BlurPage : Page
private readonly Thickness ScrollViewerMargin = UIHelper.ScrollViewerMargin;
private readonly Array BackgroundSources = Enum.GetValues(typeof(BackgroundSource));
private readonly bool IsAppWindowSupported = WindowHelper.IsAppWindowSupported;
private readonly bool IsActualThemeChangedSupported = ApiInformation.IsEventPresent("Windows.UI.Xaml.FrameworkElement", "ActualThemeChanged");

private bool isDark;
private long token;

public BlurPage() => InitializeComponent();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (IsActualThemeChangedSupported)
{ ActualThemeChanged += OnActualThemeChanged; }
ThemeHelper.UISettingChanged += OnUISettingChanged;
token = BackdropBlurBrush.RegisterPropertyChangedCallback(BackdropBlurBrush.TintColorProperty, OnTintColorPropertyChanged);
OnTintColorPropertyChanged(BackdropBlurBrush, BackdropBlurBrush.TintColorProperty);
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (IsActualThemeChangedSupported)
{ ActualThemeChanged -= OnActualThemeChanged; }
ThemeHelper.UISettingChanged -= OnUISettingChanged;
BackdropBlurBrush.UnregisterPropertyChangedCallback(BackdropBlurBrush.TintColorProperty, token);
}

private async void OnActualThemeChanged(FrameworkElement sender, object args)
private void Page_Loaded(object sender, RoutedEventArgs e)
{
if (!Dispatcher.HasThreadAccess)
_ = ThemeHelper.GetRootThemeAsync().ContinueWith(x => x.Result.IsDarkTheme()).ContinueWith(x => isDark = x.Result);
}

private async void OnUISettingChanged(bool theme)
{
if (isDark != theme)
{
await Dispatcher.ResumeForegroundAsync();
TintColor.Color = ReversalColor(TintColor.Color);
isDark = theme;
}

Color ReversalColor(in Color color)
{
return Color.FromArgb(color.A, (byte)(255 - color.R), (byte)(255 - color.G), (byte)(255 - color.B));
}
TintColor.Color = Color.FromArgb(TintColor.Color.A, (byte)(255 - TintColor.Color.R), (byte)(255 - TintColor.Color.G), (byte)(255 - TintColor.Color.B));
}

private void OnTintColorPropertyChanged(DependencyObject sender, DependencyProperty dp)
{
Color color = (Color)sender.GetValue(dp);
bool isLight = color.IsColorLight();
RequestedTheme = isLight ? ElementTheme.Light : ElementTheme.Dark;
}

private void TitleBar_BackRequested(object sender, RoutedEventArgs e)
Expand Down
8 changes: 4 additions & 4 deletions MicaDemo/Pages/MainPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
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"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
NavigationCacheMode="Enabled"
mc:Ignorable="d">
<StackPanel
x:Name="StackPanel"
Padding="20"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{StaticResource CardBackgroundFillColorDefaultBrush}"
BorderBrush="{StaticResource CardBorderBrush}"
BorderThickness="{StaticResource CardBorderThickness}"
Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
BorderBrush="{ThemeResource CardBorderBrush}"
BorderThickness="{ThemeResource CardBorderThickness}"
CornerRadius="8">
<Button
x:Name="Blur"
Expand Down
Loading

0 comments on commit 01c8a50

Please sign in to comment.