首页 > 解决方案 > 如何在运行时(UWP)更改 SystemAccentColor?

问题描述

该应用程序有GridView一个颜色,其中每个项目都是一种颜色,用户可以选择自定义 UI 以覆盖默认值SystemAccentColor(由用户在其系统上定义)。我设法获得了项目的颜色,但即使我将它分配为 SystemAccentColor 的新值,我也无法更新 UI。

private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
        // FIRST APROACH -----

        GridViewItem gridViewItem = GVColors.ContainerFromItem(e.ClickedItem) as GridViewItem;

        Ellipse ellipseItem = gridViewItem.FindDescendant<Ellipse>();

        var theColor = (SolidColorBrush)ellipseItem.Fill;

        Application.Current.Resources["SystemAccentColor"] = theColor;


        // SECOND APPROACH ----

        Windows.UI.Color theColor2 = new Windows.UI.Color
        {
            A = 1,
            R = 176,
            G = 37,
            B = 37
        };

        var root = (FrameworkElement)Window.Current.Content;
        root.Resources["SystemAccentColor"] = theColor2;
}

我目前正在阅读Diederik Krols 撰写的这篇博文 XAML Brewer:在 UWP 中使用动态系统强调色,但我想知道社区是否知道另一种在运行时更改强调色的方法(或者我不知道的方法意识到更新/刷新 UI)。

标签: c#uwp

解决方案


我将它分配为 SystemAccentColor 的新值我无法更新 UI。

由于您静态绑定 SystemAccentColor 并且它没有实现INotifyPropertyChanged接口,因此即使 SystemAccentColor 的值发生变化,与之绑定的 UI 也不会直接更新。

根据您的要求,您可以添加一个实现 INotifyPropertyChanged 接口的类,并在其中添加 SystemAccentColor 作为属性。然后在中初始化类实例Application.Resources。之后,将 UI 与 SystemAccentColor 属性绑定。例如,我创建了一个名为 SystemAccentColorSetting 的类。

SystemAccentColorSetting.cs:

public class SystemAccentColorSetting : INotifyPropertyChanged
{
    private SolidColorBrush systemAccentColor = new SolidColorBrush(Colors.Red);
    public SolidColorBrush SystemAccentColor
    {
        get { 
            return systemAccentColor; 
        }
        set { 
            systemAccentColor = value; OnPropertyChanged(); 
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

应用程序.xaml:

<Application.Resources>
    <ResourceDictionary>
        <local:SystemAccentColorSetting x:Key="SystemAccentColorSetting"/>
    </ResourceDictionary>
</Application.Resources>

用法:

假设我们将 Button 的 Background 与 SystemAccentColor 属性绑定。

.xaml:

<Button x:Name="MyButton" Background="{Binding SystemAccentColor, Source={StaticResource SystemAccentColorSetting}}">hello</Button>

。CS:

如果要更改 Background 的值,只需更改 SystemAccentColor 属性。

private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
    GridViewItem gridViewItem = GVColors.ContainerFromItem(e.ClickedItem) as GridViewItem;
    Ellipse ellipseItem = gridViewItem.FindDescendant<Ellipse>();
    var theColor = (SolidColorBrush)ellipseItem.Fill;

    ((SystemAccentColorSetting)Application.Current.Resources["SystemAccentColorSetting"]).SystemAccentColor = theColor;
}

推荐阅读