kux*_*kux 4 c# xaml maui .net-maui
如何在代码后面找到带有密钥的资源?
也相当于{DynamicResource}/{StaticResource}标记扩展。
在 WPF 中,解决方案是:
Style=(Style)FindResource("MyStyleKey");
How to do this in MAUI?,因为 FindResource 不存在。
我不想手动挖掘 Application.Resources 中的所有合并字典
我想知道为什么还没人问,我是否忽略了这个简单的解决方案?
编辑1:
哈哈,好的,我没有想到要检查 ResourceDictionary 是否递归搜索自身。但这只是工作的一半。你仍然需要向后遍历当前元素树。
因此,为什么 FindResource 没有默认实现的问题仍然是合理的?或者其他地方是否已经有一个函数可以做到这一点?
编辑2:
我把问题带到了更重要的一点:如何找到资源,而不是如何分配。
最初的问题是“如何在代码后面分配带有键的样式”
一种简单的方法是创建自定义静态字典来访问 App.xaml.cs 中的合并字典
在我的例子中,它将是Colors.xaml作为资源字典。路径是Resources/Styles/Colors.xaml; assembly=SampleApp
在此字典中,颜色作为键,资源字典作为值
在App.xaml中
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)
在App.xaml.cs中
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
ResourceDictionary = new Dictionary<string, ResourceDictionary>();
foreach (var dictionary in Application.Current.Resources.MergedDictionaries)
{
string key = dictionary.Source.OriginalString.Split(';').First().Split('/').Last().Split('.').First(); // Alternatively If you are good in Regex you can use that as well
ResourceDictionary.Add(key, dictionary);
}
}
public static Dictionary<string,ResourceDictionary> ResourceDictionary;
}
Run Code Online (Sandbox Code Playgroud)
在 C# 代码中使用字典
(Color)App.ResourceDictionary["Colors"]["ColorKey"]
Run Code Online (Sandbox Code Playgroud)
小智 6
AppTheme currentTheme = Application.Current.RequestedTheme;
// The First Dictionary merged in App.xaml is the Colors Dictionary
var rd = App.Current.Resources.MergedDictionaries.First();
if(currentTheme== AppTheme.Dark)
{
_barColor = (Color)rd["Secondary"];
_borderColor = (Color)rd["Gray600"];
_TrackColor = (Color)rd["Tertiary"];
}
else
{
_barColor = (Color)rd["Primary"];
_borderColor = (Color)rd["Gray950"];
_TrackColor = (Color)rd["Secondary"];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9448 次 |
| 最近记录: |