如何在代码后台查找具有特定键的资源?[MAUI]

5

如何在代码后台查找具有关键字的资源?

还有{DynamicResource}/{StaticResource}标记扩展的等价物。

在WPF中,解决方案是:
Style=(Style)FindResource("MyStyleKey");
那么在MAUI中该怎么做呢?因为FindResource不存在。

我不想手动查看Application.Resources中所有合并的字典。

我想知道为什么没有人问过这个问题,我是否忽略了简单的解决方案?

编辑1:

哈哈,好吧,我没有想到检查ResourceDictionary是否递归搜索自身。但这只是一半的工作。 你仍然需要向后遍历当前元素树。

因此,问题仍然是合理的:为什么默认情况下没有实现FindResource?或者是否已经在其他地方有一个完全符合要求的函数?

编辑2:

我把问题带到了更重要的点上,如何找到资源,而不是如何分配。
最初的问题是“如何在代码后台分配具有关键字的样式”。


1
那么 Style = Application.Resources["MyStyleKey"] as Style 怎么样? - Shaw
@Shaw 这假设它在 Application.Resources 中。但我不知道它在哪里,所以问题是如何查找它,而不是如何分配它。 - Kux
6个回答

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

是的,我知道。但是当颜色在本地被覆盖时,被覆盖的值不会被使用。 - Kux

6

一种简单的方法是创建一个自定义静态字典来访问在App.xaml.cs中合并的字典

在我的情况下,它将是Colors.xaml作为资源字典。 路径为Resources/Styles/Colors.xaml;assembly=SampleApp

在这个字典中,Colors作为键,ResourceDictionary作为值

在App.xaml中

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

In 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"]

谢谢。不幸的是,这并没有回答你可以在哪个ResourceDictionary中找到资源的问题。 - Kux
我已经根据使用案例进行了编辑。希望这回答了你的问题。 - valliappan ramanathan
我的意思是这不是我的问题的答案。我不想创建资源,我想找到现有的资源!这个问题已经得到了回答。https://dev59.com/Y8Tsa4cB1Zd3GeqPAZmC#72610077 - Kux

3
只要没有默认值,这里就是我的替代品。
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;
    }
}

函数的工作不能仅仅是可行的,它必须完美无缺。

由于我对框架的深入了解不足,所以我不能确定逻辑是否完美。因此,欢迎任何纠正。


我不知道如何在我的情况下使用。 - Nicolas Oñate

0

我使用这个替代方案。如果我从代码中尝试使用不存在的颜色,也会出现编译错误。我知道这不是你的问题的答案,但根据我的经验,大多数颜色和图标字体都需要从代码中访问。有时你仍然需要获取你的资源样式。

    public static class AppColors
    {
    //------------ Base Colors ----------------------------------//
    public static Color Primary800Color = Color.FromHex("#2B272B");
    public static Color Primary500Color = Color.FromHex("#2A2829");
    public static Color Primary200Color = Color.FromHex("#353334");
    public static Color Primary100Color = Color.FromHex("#454243");

    //public static Color SignalGreenColor = ColorConverters.FromHex("#2BDB8C");
    //public static Color SignalYellowColor = ColorConverters.FromHex("#F5E500");
    public static Color SignalRedColor = Color.FromHex("#FF675C");
    public static Color SignalBlueColor = Color.FromHex("#1492FF");//#0073D7 //#005EAB

    public static Color BlackColor = Color.FromHex("#000000");
    public static Color WhiteColor = Color.FromHex("#ffffff");

    public static Color Gray900Color = Color.FromHex("#1A1A1A");
    public static Color Gray700Color = Color.FromHex("#878787");
    public static Color Gray400Color = Color.FromHex("#BBBBBB");
    public static Color Gray300Color = Color.FromHex("#DEDEDE");
    public static Color Gray200Color = Color.FromHex("#EAEAEA");
    public static Color Gray100Color = Color.FromHex("#FAFAFA");
   


}

public static class AppIconFont
{
    public const string Icon_right = "\uea1f";
    public const string Icon_left = "\uea20";
    public const string Icon_down = "\uea21";
    public const string Icon_up = "\uea22";
    public const string Icon_nav_back = "\uea23";
    public const string Icon_body_shape = "\uea28";
    public const string Icon_experence = "\uea29";
    public const string Icon_geo = "\uea2a";
    public const string Icon_gender = "\uea2b";
    public const string Icon_age = "\uea2c";
    
}

然后在我的样式中我这样做。

<Style TargetType="Button" ApplyToDerivedTypes="True">
        <Setter Property="BackgroundColor" Value="{x:Static ac:AppColors.SignalBlueColor}" />
        <Setter Property="FontFamily" Value="SansBold" />
        <Setter Property="TextColor" Value="{x:Static ac:AppColors.BlackColor}" />
        <Setter Property="FontSize" Value="Small" />
        <Setter Property="HeightRequest" Value="48" />
        <Setter Property="Margin" Value="12" />
        <Setter Property="CornerRadius" Value="0" />
    </Style>

0
假设样式已经有一个名为MyStyleKeyx:key属性。
如果在App.xaml中的样式。
Style style = (Style)Application.Current.Resources["MyStyleKey"];

如果在Page.xaml中的样式

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

样式可能在可视树的其他位置,因此这只是一个部分解决方案,但感谢它指引我正确的方向来实现FindResource(如果还没有这样的函数)。 - Kux

0

这与我的问题有什么关系? - Kux
1
最佳答案。由于某种原因,(Style)Application.Current.Resources["StyleKey"]无法找到{x:StaticResource StyleKey}所找到的样式,因此这解决了我的问题。希望他们能解决这个问题,或者有人解释为什么我们不能使用简单的C#方式。现在,如果您要全局使用资源字典,请将其定义为全局。 - Barreto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接