// 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 { /// /// Implements a name scope. /// public class NameScope : INameScope { /// /// Defines the NameScope attached property. /// public static readonly AttachedProperty NameScopeProperty = PerspexProperty.RegisterAttached("NameScope"); private readonly Dictionary _inner = new Dictionary(); /// /// Raised when an element is registered with the name scope. /// public event EventHandler Registered; /// /// Raised when an element is unregistered with the name scope. /// public event EventHandler Unregistered; /// /// Gets the value of the attached on a visual. /// /// The visual. /// The value of the NameScope attached property. public static INameScope GetNameScope(Control visual) { return visual.GetValue(NameScopeProperty); } /// /// Sets the value of the attached on a visual. /// /// The visual. /// The value to set. public static void SetNameScope(Control visual, INameScope value) { visual.SetValue(NameScopeProperty, value); } /// /// Registers an element with the name scope. /// /// The element name. /// The element. public void Register(string name, object element) { Contract.Requires(name != null); Contract.Requires(element != null); object existing; if (_inner.TryGetValue(name, out existing)) { if (existing != element) { throw new ArgumentException($"Control with the name '{name}' already registered."); } } else { _inner.Add(name, element); Registered?.Invoke(this, new NameScopeEventArgs(name, element)); } } /// /// Finds a named element in the name scope. /// /// The name. /// The element, or null if the name was not found. public object Find(string name) { Contract.Requires(name != null); object result; _inner.TryGetValue(name, out result); return result; } /// /// Unregisters an element with the name scope. /// /// The name. public void Unregister(string name) { Contract.Requires(name != null); object element; if (_inner.TryGetValue(name, out element)) { _inner.Remove(name); Unregistered?.Invoke(this, new NameScopeEventArgs(name, element)); } } } }