首页 > 解决方案 > Xamarin Forms - 如何从 MergedDictionaries 中选择 C# 中的资源

问题描述

有人可以向我展示用于在下面的 IconResources.xaml 文件中选择 AdjustmentsIcon 样式的 Linq 查询吗?

我知道你可以到达...

Application.Current.Resources["key"]

但我正在寻找一种代码有效的方法来使用 Linq 从 MergeDictionary 中选择样式。

应用程序.xaml

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:font="clr-namespace:WP.Device.Resources"
             xmlns:resources="clr-namespace:WP.Device.Resources"
             x:Class="WP.Device.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <resources:IconResources />
                <resources:ColorResources />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

IconResources.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:font="clr-namespace:WP.Device.Resources"
                    xmlns:resources="clr-namespace:WP.Device.Resources"
                    x:Class="WP.Device.Resources.IconResources">
    <ResourceDictionary.MergedDictionaries>
        <resources:ColorResources />
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="Label" x:Key="AddNewIcon">
        <Setter Property="FontSize" Value="30" />
    </Style>
    <Style TargetType="Label" x:Key="AdjustmentsIcon">
        <Setter Property="FontSize" Value="40" />
    </Style>
</ResourceDictionary>

更新

我很欣赏@pinedax的回答,但对我来说......

Application.Current.Resources["key"]

没有来自合并字典的键。我无法制定一个 Linq 查询来找到我的风格,但我写了以下有效的...

public Style FindStyle(ResourceDictionary resourceDictionary, string key)
{
    Style style = resourceDictionary.ContainsKey(key) ? resourceDictionary[key] as Style : null;

    if (style == null)
    {
        foreach (var mergedDictionary in resourceDictionary.MergedDictionaries)
        {
            style = FindStyle(mergedDictionary, key);

            if (style != null) break;
        }
    }
    
    return style;
}

并被称为...

Style errorIcon = FindStyle(Application.Current.Resources, "AddNewIcon");

标签: linqxamarinxamarin.forms

解决方案


Application.Current.Resources.TryGetValue("key", out var result);

还将查看合并的字典如@pinedax 所述)。


推荐阅读