From bf4bb7d54c2373e15cbfa30b97ad2d00b1e9fb18 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Sat, 2 Sep 2017 01:01:46 +0200 Subject: [PATCH] Added TryFindResource extension method. `FindResource` can be ambiguous because it returns `AvaloniaProperty.UnsetValue` in the case of a resource not being found, which is a valid resource value. `TryFindResource` removes this ambiguity. `FindResource` has been left in for API compatibility with other frameworks. --- .../Controls/ResourceProviderExtensions.cs | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/Avalonia.Styling/Controls/ResourceProviderExtensions.cs b/src/Avalonia.Styling/Controls/ResourceProviderExtensions.cs index c96e8ea7f3..1f25fa132d 100644 --- a/src/Avalonia.Styling/Controls/ResourceProviderExtensions.cs +++ b/src/Avalonia.Styling/Controls/ResourceProviderExtensions.cs @@ -1,8 +1,6 @@ using System; -using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; -using System.Text; namespace Avalonia.Controls { @@ -15,6 +13,23 @@ namespace Avalonia.Controls /// The resource key. /// The resource, or if not found. public static object FindResource(this IResourceNode control, string key) + { + if (control.TryFindResource(key, out var value)) + { + return value; + } + + return AvaloniaProperty.UnsetValue; + } + + /// + /// Tries to the specified resource by searching up the logical tree and then global styles. + /// + /// The control. + /// The resource key. + /// On return, contains the resource if found, otherwise null. + /// True if the resource was found; otherwise false. + public static bool TryFindResource(this IResourceNode control, string key, out object value) { Contract.Requires(control != null); Contract.Requires(key != null); @@ -25,16 +40,17 @@ namespace Avalonia.Controls { if (current is IResourceNode host) { - if (host.TryGetResource(key, out var value)) + if (host.TryGetResource(key, out value)) { - return value; + return true; } } current = current.ResourceParent; } - return AvaloniaProperty.UnsetValue; + value = null; + return false; } public static IObservable GetResourceObservable(this IResourceNode target, string key)