c# - 如何在运行时(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)。
解决方案
我将它分配为 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;
}
推荐阅读
- r - 如何为按变量分组的 p 值创建列
- flutter - TabBar 没有 TabController
- c++ - 如何在 GCC 中使用 c++20 模块?
- java - 使用 XWork2 的 ClassNotFoundException
- forms - CodeIgniter - 保存方法和重定向
- google-apps-script - 如何在 Google 课堂中按标题删除课程作业(作业)
- timestamp - 在发送前更改数据包的时间戳
- flutter - 如何使此页面在所有屏幕上都响应?
- c# - 返回一个包含每个内部数组元素数量的整数数组c#
- python - 仅使用 numpy 的 Python 中的神经网络