Browse Source

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.
pull/1130/head
Steven Kirk 9 years ago
parent
commit
bf4bb7d54c
  1. 26
      src/Avalonia.Styling/Controls/ResourceProviderExtensions.cs

26
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
/// <param name="key">The resource key.</param>
/// <returns>The resource, or <see cref="AvaloniaProperty.UnsetValue"/> if not found.</returns>
public static object FindResource(this IResourceNode control, string key)
{
if (control.TryFindResource(key, out var value))
{
return value;
}
return AvaloniaProperty.UnsetValue;
}
/// <summary>
/// Tries to the specified resource by searching up the logical tree and then global styles.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="key">The resource key.</param>
/// <param name="value">On return, contains the resource if found, otherwise null.</param>
/// <returns>True if the resource was found; otherwise false.</returns>
public static bool TryFindResource(this IResourceNode control, string key, out object value)
{
Contract.Requires<ArgumentNullException>(control != null);
Contract.Requires<ArgumentNullException>(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<object> GetResourceObservable(this IResourceNode target, string key)

Loading…
Cancel
Save