52ll.org
52ll.org

winui3 主题设置改为下拉选择

效果

https://52ll.org/wp-content/uploads/2023/10/Snipaste_2023-10-17_10-14-54.png

实现

xaml布局

<ComboBox x:Name="ThemeComboBox" SelectedItem="{x:Bind ViewModel.ElementTheme, Mode=TwoWay}" FontSize="15" Margin="{StaticResource XSmallTopMargin}">
    <ComboBox.ItemTemplate>
        <DataTemplate x:DataType="xaml:ElementTheme">
            <TextBlock Text="{x:Bind}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <xaml:ElementTheme>Light</xaml:ElementTheme>
    <xaml:ElementTheme>Dark</xaml:ElementTheme>
    <xaml:ElementTheme>Default</xaml:ElementTheme>
</ComboBox>

视图模型代码修改

using System.Reflection;
using System.Windows.Input;

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

using Microsoft.UI.Xaml;

using app.Contracts.Services;
using app.Helpers;

using Windows.ApplicationModel;

namespace app.ViewModels;

public partial class SettingsViewModel : ObservableRecipient
{
    private readonly IThemeSelectorService _themeSelectorService;

    private ElementTheme _elementTheme;
    private string _versionDescription;

    public ElementTheme ElementTheme
    {
        get => _elementTheme;
        set
        {
            if (_elementTheme != value)
            {
                SetProperty(ref _elementTheme, value);
                _ = _themeSelectorService.SetThemeAsync(value);
            }
        }
    }

    public string VersionDescription
    {
        get => _versionDescription;
        set => SetProperty(ref _versionDescription, value);
    }

    public SettingsViewModel(IThemeSelectorService themeSelectorService)
    {
        _themeSelectorService = themeSelectorService;
        _elementTheme = _themeSelectorService.Theme;
        _versionDescription = GetVersionDescription();
    }

    private static string GetVersionDescription()
    {
        Version version;

        if (RuntimeHelper.IsMSIX)
        {
            var packageVersion = Package.Current.Id.Version;

            version = new(packageVersion.Major, packageVersion.Minor, packageVersion.Build, packageVersion.Revision);
        }
        else
        {
            version = Assembly.GetExecutingAssembly().GetName().Version!;
        }

        return $"{"AppDisplayName".GetLocalized()} - {version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
    }
}

注意修改的部分如下

https://52ll.org/wp-content/uploads/2023/10/diff.png

发表回复

textsms
account_circle
email

52ll.org

winui3 主题设置改为下拉选择
效果 实现 xaml布局 <ComboBox x:Name="ThemeComboBox" SelectedItem="{x:Bind ViewModel.ElementTheme, Mode=TwoWay}" FontSize="15" Margin="{StaticResource XSmallTopMargi…
扫描二维码继续阅读
2023-10-17