XAML 如何查找代码中包含关键字的资源?[MAUI]

beq87vna  于 2022-12-07  发布在  其他
关注(0)|答案(5)|浏览(140)
    • 如何查找代码中隐藏键的资源?**

也是{DynamicResource}/{StaticResource}标记延伸的对等用法。
在WPF中,解决方案为:
Style=(Style)FindResource("MyStyleKey");
如何在MAUI中执行此操作?因为FindResource不存在。
我不想手动从Application中挖掘所有合并的字典。资源😜
🤔 * 我想知道为什么还没有人问,我忽略了简单的解决方案吗?*

    • 编辑1:**

哈哈,我还没有想过要检查ResourceDictionary是否递归地搜索自己。但是这只是工作的一半。你仍然需要向后遍历当前的元素树。
因此,这个问题仍然是合理的,为什么FindResource没有在默认情况下实现?或者是否在其他地方已经有一个函数可以做到这一点?

    • 编辑2:**

我把问题带到了更重要的一点上,即如何找到资源,而不是如何分配资源。
最初的问题是"如何分配一个样式,并在代码后面添加关键字"

ygya80vv

ygya80vv1#

只要没有违约,这里就是我的替代品。

public static class ResourceHelper{

    public static object FindResource(this VisualElement o, string key) {
        while (o != null) {
            if (o.Resources.TryGetValue(key, out var r1)) return r1;
            if (o is Page) break;
            if (o is IElement e) o = e.Parent as VisualElement;
        }
        if (Application.Current.Resources.TryGetValue(key, out var r2)) return r2;
        return null;
    }
}
  • 一个函数工作是不够的,它必须完美地工作。*😜

由于我缺乏深刻的框架洞察力,我当然不确定逻辑是否完美。所以任何修正都是受欢迎的。

dsekswqp

dsekswqp2#

一种简单的方法是创建一个自定义的静态字典来访问App.xaml.cs中的合并字典
在这里,在我的情况下,它将是 * 颜色.xaml* 作为 * 资源字典 *。和路径是 * 资源/样式/颜色.xaml;程序集=示例应用程序 *
在此字典中,Colors 作为键,ResourceDictionary 作为值
在应用程序xaml中

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

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

C#程式码中的消费字典

(Color)App.ResourceDictionary["Colors"]["ColorKey"]
qnyhuwrf

qnyhuwrf3#

假设样式已经具有名为MyStyleKeyx:key属性
如果App.xaml中的样式

Style style = (Style)Application.Current.Resources["MyStyleKey"];

如果Page.xaml中的样式

Style style = (Style)Resources["MyStyleKey"];
ibps3vxo

ibps3vxo4#

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"];
}
xt0899hw

xt0899hw5#

这里有一个变通办法https://stackoverflow.com/a/73667609/3495516它的奇怪之处是你不能从代码访问,但从xaml你可以

相关问题