XAML 如何从代码中访问位于合并字典中的资源

acruukt9  于 2023-04-27  发布在  其他
关注(0)|答案(3)|浏览(194)

我在几个ResourceDicitonaries中有一堆Colors,如下所示:

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:s="clr-namespace:System;assembly=netstandard">

    <Color x:Key="Color.Background">#301536</Color>
</ResourceDictionary>

我简单地将两者都添加到App.xaml中,如下所示:

<!--Colors-->
<ResourceDictionary Source="Resources/Colors/Light.xaml"/>
<ResourceDictionary Source="Resources/Colors/Dark.xaml"/>

ResourceDicitonary文件只是一个.xaml文件,没有任何捆绑的.cs,两个字典都设置在App.xaml上,而不必在MergedDicionaries组中定义它们。
当试图从代码中访问a Color时,我无法找到它,看起来它没有添加到资源列表中。

var color = Application.Current.Resources.FirstOrDefault(f => f.Key == "Color.Background")
    .Value as Color? ?? Color.Crimson;

WPF中是否有任何方法可以访问像FindResource/TryFindResource这样的资源?
我还尝试访问/查看MergedDictionaries的内容,但由于某种原因,合并的字典总是空的。

xbp102n0

xbp102n01#

多亏了另一个人,我才能构建出这段工作代码:

internal static Color TryGetColor(string key, Color fallback)
{
    Application.Current.Resources.TryGetValue(key, out var color);

    return color as Color? ?? fallback;
}
irtuqstp

irtuqstp2#

根据您的描述,您想在APP.xaml中添加多个ResourceDictionary,但没有成功。我找到一篇关于这个问题的文章,您可以看看:
https://nicksnettravels.builttoroam.com/post/2018/09/02/Getting-Started-with-XamarinForms-and-Resource-Dictionaries.aspx

brjng4g3

brjng4g33#

或者,如果你想查找父层次结构,你可以这样做:

public static class ElementExtensions
{
    public static bool TryGetResource(this Element element, string key, [MaybeNullWhen(false)] out object value)
    {
        while (element != null)
        {
            if (element is VisualElement visualElement && visualElement.Resources.TryGetValue(key, out value))
                return true;
            if (element is Application app && app.Resources.TryGetValue(key, out value))
                return true;
            element = element.Parent;
        }

        value = null;

        return false;
    }

    public static bool TryGetResource<TResource>(
        this Element element,
        string key,
        [MaybeNullWhen(false)] out TResource resource) where TResource : class
    {
        if (element.TryGetResource(key, out object? value))
        {
            resource = value as TResource;

            return resource != null;
        }
        else
        {
            resource = default;

            return false;
        }
    }
}

它的灵感来自ResourcesExtensions的MAUI源代码,不幸的是,这是内部的。

相关问题