How to find a resource with key in code behind?
Also the equivalent to {DynamicResource}
/{StaticResource}
markup extensions.
In WPF the solution was:
Style=(Style)FindResource("MyStyleKey");
How to do this in MAUI?, because FindResource does not exist.
I don't feel like manually digging through all the merged dictionaries from Application.Resources 😜
🤔 I wonder why that no one has asked yet, have I overlooked the simple solution?
Edit1:
LOL OK It hasn't crossed my mind to check if the ResourceDictionary searches itself recursively. But this is only the half work. You still have to traverse the current element tree backwards.
Therefore, the question is still reasonable why FindResource is not implemented by default? or whether there is already a function somewhere else that does exactly that?
Edit2:
I brought the question to the more important point, How to find a resource, not how to assign.
The original question was "How to assign a Style with key in code behind"
As long there is no default, here is my substitute.
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;
}
}
It is not enough that a function works, it must work perfectly. 😜
Since I lack of deep framework insights, I am of course not sure if the logic is perfect. So any correction is welcome.