gpt4 book ai didi

c# - 如何在运行时更改 SystemAccentColor (UWP)?

转载 作者:行者123 更新时间:2023-12-03 08:44:52 25 4
gpt4 key购买 nike

该应用程序有一个 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;
}

我目前正在阅读这篇博客文章 XAML Brewer, by Diederik Krols: Using a Dynamic System Accent Color in UWP但我想知道社区是否知道另一种在运行时更改强调色的方法(或者我不知道的更新/刷新 UI 的方法)。

最佳答案

I assign it as new value for SystemAccentColor I am not able to update the UI.

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

根据您的要求,您可以添加一个实现 INotifyPropertyChanged 接口(interface)的类,并在其中添加 SystemAccentColor 作为属性。然后初始化Application.Resources中的类实例。之后,将 UI 与 SystemAccentColor 属性绑定(bind)。例如,我创建一个名为 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));
}
}

App.xaml:

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

用法:

假设我们将 Button 的背景与 SystemAccentColor 属性绑定(bind)。

.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;
}

关于c# - 如何在运行时更改 SystemAccentColor (UWP)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61928816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com