我想建立一个组合框,让用户 Select 他们希望应用程序显示的主题.

I added a combobox on my WinUI projects's settings page
The code go like this:

<!--XAML CODE-->

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

But I don't know how to defined "Themes_SelectionChanged"
(I have found some ways, but I think they're too complex to implement just this simple functionality, aren't there any simple way to acieve this?)

推荐答案

让我们假设这个组合框是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" />

UPDATE

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

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

Csharp相关问答推荐

如何从顶部提取发票号作为单词发票后的第一个匹配

图形.DrawString奇怪异常的字距调整

下拉图片点击MudBlazor

在. net毛伊岛窗口的深度链接已经创建""

将列表字符串映射为逗号分隔字符串<>

数组被内部函数租用时,如何将数组返回给ArrayPool?

在C#WinUI中,一个关于System的崩溃."由于未知原因导致执行不例外"

在实时数据库中匹配两个玩家的问题

从ASP.NET Core中的枚举字段填充 Select 选项时,将默认的第一个选项添加为 Select 元素

C#阻塞调用或await calling inside calling方法

TeamsBot SendActivityActivityTypes与ActivityTypes同步.键入不再起作用

记录类型';==运算符是否与实现IEquatable<;T&>;的类中的';equals&>方法执行等价比较?

为值对象编写自定义JsonConverter

将操作从编辑页重定向到带参数的索引页

毛伊岛.NET 8图片不再适合按钮

Azure函数正在返回值列表,但该列表在Chrome中显示为空

将两个for循环更改为一条LINQ语句

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

外部应用&&的LINQ;左外部连接&类似于PostgreSQL的查询

将ValueTask发送给调用者