XAML 如何在WinUI3中手动切换颜色主题?

svmlkihl  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(167)

我想建立一个组合框,让用户选择他们想要的应用程序显示的主题。
我在WinUI项目的设置页面上添加了一个组合框
代码如下:

<!--XAML CODE-->

<ComboBox x:Name="themeMode" SelectionChanged="Themes_SelectionChanged">
    <ComboBoxItem>Light</ComboBoxItem>
    <ComboBoxItem>Dark</ComboBoxItem>
    <ComboBoxItem>Defaut</ComboBoxItem>                    
</ComboBox>

字符串
但我不知道如何定义“主题_选择改变”

  • (我已经找到了一些方法,但我认为它们太复杂了,无法实现这个简单的功能,难道没有简单的方法来实现吗?)*
vxqlmq5t

vxqlmq5t1#

假设这个ComboBox位于MainPage.xaml中。

<ComboBox x:Name="themeMode" SelectionChanged="Themes_SelectionChanged">
    <ComboBoxItem>Light</ComboBoxItem>
    <ComboBoxItem>Dark</ComboBoxItem>
    <ComboBoxItem>Defaut</ComboBoxItem>                    
</ComboBox>

字符串
然后在MainPage.xaml.cs

private void Themes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender is ComboBox comboBox &&
        comboBox.SelectedItem is ComboBoxItem comboBoxItem &&
        comboBoxItem.Content is string themeString &&
        Enum.TryParse(themeString, out ElementTheme theme) is true)
    {
        this.RequestedTheme = theme;
    }
}


此外,代替在XAML中手动添加项,您可以通过这种方式完成。

MainPage.xaml中:

public ImmutableArray<string> ElementThemeOptions { get; } = ImmutableArray.Create(Enum.GetNames<ElementTheme>());

private void Themes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender is ComboBox comboBox &&
        comboBox.SelectedValue is string themeString &&
        Enum.TryParse(themeString, out ElementTheme theme) is true)
    {
        this.RequestedTheme = theme;
    }
}


MainPage.xaml中:

<ComboBox
    ItemsSource="{x:Bind ElementThemeOptions}"
    SelectionChanged="Themes_SelectionChanged" />

更新

不要忘记在根页面中执行此操作,在本例中为MainPage

<Window
    ...
    ...>
    <local:MainPage />
</Window>

相关问题