// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; namespace Perspex.Controls { /// /// Extension methods for . /// public static class NameScopeExtensions { /// /// Finds a named element in an . /// /// The element type. /// The name scope. /// The name. /// The named element or null if not found. public static T Find(this INameScope nameScope, string name) where T : class { Contract.Requires(nameScope != null); Contract.Requires(name != null); var result = nameScope.Find(name); if (result != null && !(result is T)) { throw new InvalidOperationException( $"Expected control '{name}' to be '{typeof(T)} but it was '{result.GetType()}'."); } return (T)result; } /// /// Gets a named element from an or throws if no element of the /// requested name was found. /// /// The element type. /// The name scope. /// The name. /// The named element. public static T Get(this INameScope nameScope, string name) where T : class { Contract.Requires(nameScope != null); Contract.Requires(name != null); var result = nameScope.Find(name); if (result == null) { throw new KeyNotFoundException($"Could not find control '{name}'."); } if (!(result is T)) { throw new InvalidOperationException( $"Expected control '{name}' to be '{typeof(T)} but it was '{result.GetType()}'."); } return (T)result; } } }