using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using JetBrains.Annotations; namespace JetBrains.UI.Avalon { /// /// Chooses a data template based on the type of the item. /// public class DataTemplateSwitchSelector : DataTemplateSelector, IEnumerable> { #region Data private readonly Dictionary _map = new Dictionary(); #endregion #region Operations /// /// Registers a data template to be returned for the objects of the given . /// public void Add([NotNull] DataTemplate template) { if(template == null) throw new ArgumentNullException("template"); Add(typeof(TType), template); } /// /// Registers a data template to be returned for the objects of the given . /// public void Add([NotNull] Type type, [NotNull] DataTemplate template) { if(type == null) throw new ArgumentNullException("type"); if(template == null) throw new ArgumentNullException("template"); _map.Add(type, template); } #endregion #region Overrides public override DataTemplate SelectTemplate(object item, DependencyObject container) { if(item == null) return null; // Take 1: exact type DataTemplate template; if(_map.TryGetValue(item.GetType(), out template)) return template; // Take 2: base type foreach(var pair in _map) { if(pair.Key.GetType().IsAssignableFrom(item.GetType())) return pair.Value; } return null; } #endregion #region IEnumerable> Members public IEnumerator> GetEnumerator() { return _map.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }