Unity IoC container: tips, tricks and dirty hacks

It took me two years to write this post. Each time I started writing it, it suffered from gradual and seemingly unavoidable feature creep: should I mention dependency inversion principle? What about SOLID principles in general? What about testability? The list goes on and on. But it was a recent interesting discussion with a friend about the use (and abuse) of dependency injection that prompted me to finally finish it.

I have been using Unity IoC container for a while now and in the process I have managed to ”abuse” it in every possible way so I hope this post covers some of the more advanced and intricate usage scenarios you may ever come across.

Trivial case

In case you have never used Unity before, the behaviour of the container is pretty trivial: call Register<T,TImpl>() on a number of types then make a call to Resolve<T> and with a bit of luck you will get a instance of it:

[TestFixture]
    class TrivialTests
    {
        [Test]
        public void TrivialOne()
        {
            var container = new UnityContainer();

            container.RegisterType<IBar, Bar>();

            var instance = container.Resolve<IBar>();

            Assert.NotNull(instance);
        }
    }

    internal class Bar : IBar {}
    internal interface IBar {}

Implementing a factory with Unityeven

Unity is not only able to resolve an implementation of a particular interface; it may also help in resolving dependencies when the type to be instantiated is known ( if it has not been registered with the container):

    [TestFixture]
    public class ObjectBuildupTest
    {
        [Test]
        public void ObjectBuildup()
        {
            var container = new UnityContainer();
            container.RegisterType<ISomeService, SomeService>();

            var anInstance = container.Resolve<ObjectWithDependencies>();

            Assert.NotNull(anInstance);
        }
    }

    public class ObjectWithDependencies
    {
        public ObjectWithDependencies(ISomeService  someService)
        {
            if (someService == null) throw new ArgumentNullException("someService");
        }
    }

    public interface ISomeService {}
    public class SomeService : ISomeService {}

As you can see from the code above, even though the type “ObjectWithDependencies” has not been registered with the container, Unity was able to correctly instantiate it and inject it with previously registered dependency. Such functionality may come very useful when implementing a factory: we know what we want to instantiate but not necessarily want to be bothered with instantiating all the dependencies. The following sample illustrates this approach.

    [TestFixture]
    public class FactoryTest
    {
        [Test]
        public void UnityBasedFactoryTest()
        {
            var container = new UnityContainer();

            container.RegisterType<ISomeService, SomeService>();
            container.RegisterType<ISomeFactory, SomeFactory>();

            var factory = container.Resolve<ISomeFactory>();

            Assert.NotNull(factory.ManufactureAnObject("A"));
        }
    }

    public interface ISomeFactory
    {
        ICommonInterface ManufactureAnObject(string anArgument);
    }

    public class SomeFactory : ISomeFactory
    {
        private readonly IUnityContainer _container;

        public SomeFactory(IUnityContainer container)
        {
            _container = container;
        }

        public ICommonInterface ManufactureAnObject(string anArgument)
        {
            switch(anArgument)
            {
                case "A":
                    return _container.Resolve<TypeA>();
                case "B":
                    return _container.Resolve<TypeB>();
                default:
                    throw new NotSupportedException();
            }
        }
    }

    public interface ICommonInterface {}

    public class TypeB : ICommonInterface
    {
        public TypeB(ISomeService someService)
        {            
        }
    }

    public class TypeA : ICommonInterface
    {
        public TypeA(ISomeService someService)
        {            
        }
    }

As you have probably noticed our factory requires an instance of IUnityContainer, luckily the container auto-registers itself, so whenever and instance of IUnityContainer is required, one will be injected without any fuss. Purists may frown upon direct use of the container, but in my opinion this is one of the very rare cases where it can be justified.

Multiple implementations of the same contract

The following example illustrates how to register multiple implementations of the same interface. Each registration is done with a particular key (quite a common feature among IoC containers) and then when resolving it we need to specify the key to get a particular implementation:

    [TestFixture]
    public class MultipleImplementationsTests
    {
        [Test]
        public void MultipleImplementations_ResolveCorrectly()
        {
            var container = new UnityContainer();
            container.RegisterType<IFooBar, SomeFooBar>("first");
            container.RegisterType<IFooBar, OtherFooBar>("second");

            Assert.NotNull(container.Resolve<IFooBar>("first"));
            Assert.NotNull(container.Resolve<IFooBar>("second"));
            Assert.Throws<ResolutionFailedException>(() => container.Resolve<IFooBar>());
        }
    }

    public interface IFooBar {}
    public class OtherFooBar : IFooBar {}
    public class SomeFooBar : IFooBar {}

This functionality can again be used to implement a factory of sorts but in general it is not that interesting until we get to the next point.

Building a composite

Having a multiple implementations of a particular contract registered with the container is the stepping stone to building a composite, as the following sample illustrates:

    [TestFixture]
    public class CompositeTests
    {
        [Test]
        public void BuildComposite()
        {
            var container = new UnityContainer();
            container.RegisterType<IFoo, SomeFoo>("first");
            container.RegisterType<IFoo, AnotherFoo>("second");
            container.RegisterType<IFoo, CompositeFoo>();

            var instanceOfFoo = container.Resolve<IFoo>();

            Assert.IsInstanceOf<CompositeFoo>(instanceOfFoo);
        }
    }

    public class CompositeFoo : IFoo
    {
        public CompositeFoo(IFoo[] others)
        {
            Debug.Assert(others != null);
            Debug.Assert(others.Any());
        }
    }

    public class AnotherFoo : IFoo {}
    public class SomeFoo : IFoo {}
    public interface IFoo {}

Composite in this case “consumes” an array of child objects and in a sense “sucks in” every implementation of IFoo registered with a key. This is an important aspect: if you were to register composite with a key, it would try to instantiate itself leading in immediately to StackOverflowException. The other interesting aspect is the fact that the composite requires an argument of type IChild[]. I am not sure about you but I personally find arrays very much 20th century and would rather have IEnumerable<IChild> injected, sadly Unity does not support it out of the box. There is however a workaround for it which I will share with you later.

Building chain of responsibility

Another interesting use case for naming your registrations is the implementation of Chain Of Responsibility pattern as the following sample illustrates:

    [TestFixture]
    class ChainOfResponsibilityTests
    {
        [Test]
        public void BuildChain()
        {
            var container = new UnityContainer();
            container.RegisterType<IChainLink, LastLink>("last");
            container.RegisterType<IChainLink, SecondLink>("second",
                                                           new InjectionConstructor(
                                                               new ResolvedParameter<IChainLink>("last")));
            container.RegisterType<IChainLink, FirstLink>(new InjectionConstructor(
                                                               new ResolvedParameter<IChainLink>("second")));

            var firstLink = container.Resolve<IChainLink>();

            Assert.IsInstanceOf<FirstLink>(firstLink);
        }
    }

    internal interface IChainLink {}

    internal class FirstLink : IChainLink
    {
        public FirstLink(IChainLink nextLink)
        {
            if (nextLink == null) throw new ArgumentNullException("nextLink");
        }
    }

    internal class SecondLink : IChainLink
    {
        public SecondLink(IChainLink nextLink)
        {
            if (nextLink == null) throw new ArgumentNullException("nextLink");
        }
    }

    internal class LastLink : IChainLink {}

 

In this case we need to resort to pointing each registered element of the chain to its predecessor which is achieved using ResolvedParameter<T>(name). This way we have full control as to what registration gets injected where. This may come helpful in cases where different implementations of the same contract are to be injected in different places.

Injecting the same object in multiple places in the object graph (semi-singleton)

Unity has a very interesting feature which allows the same object to be injected and shared in multiple places in the object graph. Let’s consider the following object diagram

:image

As you can see both the parent and the children contain references to an instance of Service. Standard behaviour of the IoC container is to inject new instance of the dependency into every object in the graph, this however may not be what we want:

image

In order to solve this conundrum Unity provides PerResolveLifetimeManager which within a single call to Resolve<T>() will create an instance of particular type and reuse it wherever required as the next sample illustrates:

    [TestFixture]
    public class PerResolutionLifetimeTests
    {
        [Test]
        public void Regiser_WithPerResolveLifetimeManager_ContainerInjectsSameInstance()
        {
            var container = new UnityContainer();
            container.RegisterType<IService, AService>(new PerResolveLifetimeManager());
            container.RegisterType<IParent, Parent>();
            container.RegisterType<IChild, Child>();

            var parent = container.Resolve<IParent>();

            Assert.AreSame(parent.Service, parent.Child.Service);
        }
    }

    public interface IService {}
    public class AService : IService {}
    public interface IChild
    {
        IService Service { get; set; }
    }

    public class Child : IChild
    {
        public IService Service { get; set; }

        public Child(IService service)
        {
            Service = service;
        }
    }

    public interface IParent
    {
        IChild Child { get; set; }
        IService Service { get; set; }
    }

    public class Parent : IParent
    {
        public IChild Child { get; set; }
        public IService Service { get; set; }

        public Parent(IChild child, IService service)
        {
            Child = child;
            Service = service;
        }
    }

Eternal problem: Chicken and Egg

Now there is an interesting chicken and egg problem which may seem to be impossible to solve using IoC container:

    
    public interface IEgg
    {
        IChicken Chicken { get; set; }
    }

    public interface IChicken
    {
        IEgg Egg { get; set; }
    }

    public class Chicken : IChicken
    {
        public IEgg Egg { get; set; }
    }

    public class Egg : IEgg
    {
        public Egg(IChicken chicken)
        {
            Chicken = chicken;
        }

        public IChicken Chicken
        {
            get;
            set;
        }
    }

As you can see we have a circular dependency going on here (Chicken “contains” an egg, while the egg points to its parent). This may seem to be a hopeless case but there is a solution to it: we need to combine property injection with PerResolveLifetimeManager:

[Test]
public void BuildObjectGraphWithCircularDependency()
{
    var container = new UnityContainer();

    container.RegisterType<IChicken, Chicken>(new PerResolveLifetimeManager(), new InjectionProperty("Egg"));
    container.RegisterType<IEgg, Egg>();

    var chicken = container.Resolve<IChicken>();

    Assert.AreSame(chicken, chicken.Egg.Chicken);
}

The magic above works as follows: container instantiates an instance of the Chicken class and then tries to resolve the Egg dependency. Egg in turn requires another instance of Chicken, luckily the Chicken class has been registered with PerResolveLifetimeManager which means it that instance of it can be reused in building the Egg. I think the case above is the only one I can think of where the use of property injection could be justified.

 

IoC and Interface segregation principle

There are some cases where a single type implements multiple contracts (interfaces). If you follow interface segregation principle this may lead to some troublesome cases:

[Test]
public void Resolve_ObjectDependantOnBaseInterface_ResolutionFails()
{
    var container = new UnityContainer();
    
    container.RegisterType<IDerived, Derived>();
    container.RegisterType<IDependsOnBase, DependsOnBase>();

    Assert.Throws<ResolutionFailedException>(() => container.Resolve<IDependsOnBase>());
}

public interface IBase { }
internal interface IDerived : IBase { }
internal class Derived : IDerived { }

public interface IDependsOnBase { }

public class DependsOnBase : IDependsOnBase
{
     public DependsOnBase(IBase dependency){}
}

As you can see from the code above, Derived implements IDerived which in turn is an instance of IBase. Inspite of that, resolution of DependsOnBase fails miserably. The reason is obviously the fact that there is no explicit implementation of IBase registered with the container. We could circumvent the problem by registering the Derived as type implementing the IBase interface. This approach would work but what if Derived implements more than one interface? There is however an easy way to work around the issue and this requires a hint to the container that instead of IBase it should search for an implementation of IDerived:

[Test]
public void Resolve_ObjectDependantOnBaseInterface_ResolutionSucceeds()
{
    var container = new UnityContainer();

    container.RegisterType<IDerived, Derived>();
    container.RegisterType<IDependsOnBase, DependsOnBase>(new InjectionConstructor(typeof(IDerived)));

    Assert.DoesNotThrow(() => container.Resolve<IDependsOnBase>());
}

This way btw it is the way to construct a composite using IEnumerable<> instead of an array as mentioned previously.

Overriding constructor parameters

The final set of Unity tricks deals with overriding constructor parameters. As you may remember we did this to a certain extent when registering individual elements of the chain of responsibility. There are two ways to do it: we can either instruct container at the time of registration to use specific instance of the parameters, or override parameter value at the time of resolution. Following sample illustrates both techniques.

[TestFixture]
public class ConstructorParameters
{
    [Test]
    public void OverridingCtorParams()
    {
        var container = new UnityContainer();
        container.RegisterType<SomeType>(new InjectionConstructor("Boo"));
        
        var firstInstance = container.Resolve<SomeType>();
        Assert.AreEqual("Boo", firstInstance.Message);

        var secondInstance = container.Resolve<SomeType>( new ParameterOverride("message", "Baa"));
        Assert.AreEqual("Baa", secondInstance.Message);
    }
}

public class SomeType
{
    public string Message { get; set; }

    public SomeType(string message)
    {
        Message = message;
    }
}
April 14 2012

What’s wrong with Windows?

Ever since the very early preview of Windows 8 much of the .NET developer community have been doing nothing but whingeing like a bunch old squaws along the lines of “Microsoft abandons .NET! and we will all have to program now in [javascript|HTML5|COM|C|C++]”, etc. The whingeing has been to a large extent fuelled by the cries of HTML/Javascript monkeys who had a field day at the expense of XAML/.NET developer: “Haha, all your time spent mastering XAML/.NET etc. has been just a waste. Who’s the daddy now?”. The cries got so loud recently that I find it difficult to sleep at night so let me take this opportunity and explain in plain English why Microsoft is doing what it’s doing with Windows 8.

There is nothing wrong with Windows…

..and this exactly is the fundamental problem. Microsoft finds it more and more difficult to persuade existing customers to upgrade to the latest and greatest version of the operating system. If you happen to live in the UK you must have seen the latest “I’m a PC” adverts where someone’s home is being converted into a computer shop and they leave it with their own chosen laptop/desktop once they’ve realised how much better modern computers are than their old, “good enough” PC. Why is Microsoft paying for those adverts? The only way to sell the new operating system is to sell it preinstalled on a new device. If you consider what home computers are used for (mainly browsing the net), there is simply no need to buy a new one unless the old one is dead. And would anyone you know outside of IT ever upgrade their OS? What for? And this is exactly Microsoft’s problem.

Come forth the consumer device…

So the PC is bought and stays at your average home forever (until it dies basically) whereas it’s remote cousin mobile phone is being upgraded every 12-24 months. And every one of those phones needs and OS license. Hmmm, now here’s an idea. How about the tablet fellow? What is his lifespan? As a (let’s face it) fashion accessory it is bound to have a similar “time to live” which means another OS license every 2-4 yrs. And this exactly is the ball Microsoft wants to play and I do not blame them for it.

September 18 2011

Architecting UI plug-ins for PRISM applications

It often happens that a particular feature of an application is not used very often, but when you need it you would like it to be accessible easily and without hassle: think calculator in an order entry program. Surely the user can live without it and use the calculator provided with the OS, but what if he could access a simple calculator within a click or two inside the application itself? I could give you more examples like this, but they all fall under the same umbrella of add-ons or plug-ins. Things you surely could live without but having them handy makes the work so much easier.

As it happens I have recently built similar functionality into a PRISM application and the rest of the post describes how to do it in a (hopefully) more less generic fashion.

The plan

I envisioned a plug-in to be  visual “gadget” which the user could access through a window hosting all the plug-ins available in an application in a fashion similar to Visual Studio’s Toolbox. The important thing here is the fact that each plug-in would need to provide it’s own UI: at the end of the day the application cannot up-front provide UI for plug-ins which have not yet been written. Given these requirement I came up with the following plan:

  1. The application’s main window would provide screen estate for displaying all the plug-ins in form of a PRISM’s view region
  2. The plug-ins view region would be filled by a PluginsView containing an ItemsControl which would wrap each individual plug-in into expander
  3. Underlying View Model would simply expose a collection of IPlugin elements which could be bound to the view’s item control

The Plugin

Each of the plug-ins is required to implement IPlugin interface which first of all allows it to be discovered by the PluginHost and secondly forces the plug-in to expose a “View” of sorts which can be displayed to the user. As we’re in the PRISM world here, I would expect the View to be also injected into plug-in, but it is not strictly speaking required. Each plug-in also needs to provide user readable name which will be displayed in the UI.

/// <summary>
/// Common interface for all plugins
/// </summary>
public interface IPlugin
{
    /// <summary>
    /// Gets the name of the plugin.
    /// </summary>
    /// <value>The name.</value>
    string Name { get;  }

    /// <summary>
    /// Gets the UI representation of the plugin.
    /// </summary>
    /// <value>The view.</value>
    object View { get; }
}

All the plug-ins need to be registered with the IoC container and this, in case of PRISM applications is usually done during module initialization. One thing which has to be kept in mind in such case is to give unique “key” (name) to each plug-in during registration as there will be more than one implementation of IPlugin available:

public class PluginsModule : IModule
{
    private readonly IUnityContainer _unityContainer;

    public PluginsModule(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;
    }

    public void Initialize()
    {
        _unityContainer.RegisterType<ICalculatorPluginView, CalculatorPluginView>();
        _unityContainer.RegisterType<INewsPluginView, NewsPluginView>();

        _unityContainer.RegisterType<IPlugin, CalculatorPlugin>("Calculator");
        _unityContainer.RegisterType<IPlugin, NewsPlugin>("News");
    }
}

 

The PluginHost

The role of the plug-in host is to simply consume all the implementations of IPlugin available in the application and expose them in a single collection. The simplest way to achieve that is to get them injected into the host by an IoC container. I was toying with the idea of using MEF for this purpose but at the end of the day settled for simplicity  and decided that Unity which is anyway used by PRISM will do the job as well. The following code fragment shows the inner workings of the host. As you can see the constructor gets all the implementations of IPlugin as an array which may seem a bit awkward, but this is what Unity expects out of the box. Having said that it is possible to inject an IEnumerable<IPlugin> which would seem more natural but it requires extra parameter when it comes to registering of the PluginHost with the container.

/// <summary>
/// Hosts all the plugins in the application
/// </summary>
public class PluginHost
{
    private readonly IPluginHostView _view;
    private readonly IPlugin[] _plugins;

    /// <summary>
    /// Initializes a new instance of the <see cref="PluginHost"/> class.
    /// </summary>
    /// <param name="view">The view.</param>
    /// <param name="plugins">The plugins.</param>
    public PluginHost(IPluginHostView view, IPlugin[] plugins)
    {
        _view = view;
        _plugins = plugins;
        _view.DataContext = this;
    }

    public IPluginHostView View
    {
        get { return _view; }
    }

    /// <summary>
    /// Gets the list of all the plugins available.
    /// </summary>
    /// <value>The plugins.</value>
    public IEnumerable<IPlugin> Plugins
    {
        get
        {
            return _plugins;
        }
    }
}

The PluginHostView

The purpose of the view is to show all the available plug-ins, each with his own specific UI. There is nothing magical about it apart from the fact that the item control uses item template which in turn uses plugin-provided UI as a content for the expander. I settled for the expander as I wanted to allow the user to collapse or expand them as and when required.

<Grid>
    <ItemsControl ItemsSource="{Binding Plugins}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Expander Margin="5,5,5,0"
                          Header="{Binding Name}"
                          Content="{Binding View}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

 

Implementing a plug-in

Now given all the groundwork implementing a plug-in is a doodle. The code is fundamentally no different to any other view/view-model combo as the sample below illustrates:

public class NewsPlugin : IPlugin
{
    private readonly INewsPluginView _view;

    public NewsPlugin(INewsPluginView view)
    {
        _view = view;
        _view.DataContext = this;
    }

    /// <summary>
    /// Gets the name of the plugin.
    /// </summary>
    /// <value>The name.</value>
    public string Name
    {
        get { return "Latest News"; }
    }

    /// <summary>
    /// Gets the UI representation of the plugin.
    /// </summary>
    /// <value>The view.</value>
    public object View
    {
        get { return _view;  }
    }

    /// <summary>
    /// Gets the news.
    /// </summary>
    /// <value>The news.</value>
    public IEnumerable<string> News
    {
        get
        {
            return new[]
                       {
                           "Frogs Invade Pratt's Bottom...",
                           "Developer's bonuses set to triple in 2012",
                           "Read more..."
                       };
        }
    }
}

 

Wrapping it all up

The attached sample application illustrates how all the parts interact together. The full source code can be found here.

image

October 19 2010

WPF DomainUpDown control

There is an MSDN page which made me chuckle recently when I was looking for a WPF equivalent of winform’s DomainUpDown control: according to the page the equivalent control in WPF is a TextBlock and two repeater buttons :) Cobbling together controls and code every time a need arises is not very appealing, so I decided to give it a go and create a WPF equivalent. The idea behind the DomainUpDown control is to allow the user to pick a value from a predefined list in a fashion similar to that of a ComboBox. The difference however is the fact that DomainUpDown does not require as much screen estate as the combo.  As you can imagine the control requires two dependency properties: one containing currently selected value and the other containing the list of “options”; when you click up or down either the next or the previous value from the list is selected. The following XAML illustrates how to use the control:

   1:         <Controls:DomainUpDown 
   2:                                 Value="{Binding CurrentValue}"
   3:                                 Items="{Binding Strings}" />

 

The sample application (screenshot below) illustrates various use cases of the control, including setting the value which is not present in the list of predefined “options” as well as behaviour of control when the list of has not been set.

image 

The code for the control and the sample app is available as part of the SharpFellows.Toolkit so I won’t bother you with the details here, but the majority of it is related to synchronisation of current value and its index in the list of options. This is important  when you set the value through binding (or code behind) and click either up or down buttons. One would expect that the correct next/previous value from the list is selected but this is where the original fails miserably and I found this behaviour rather annoying. The control also supports selecting the value using up/down keys and for those really inquisitive the full code is listed below.

using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace SharpFellows.Toolkit.Controls
{
    /// <summary>
    /// WPF DomainUpDown control
    /// </summary>
    [TemplatePart(Name = &quot;PART_UpButton&quot;, Type = typeof(RepeatButton))]
    [TemplatePart(Name = &quot;PART_DownButton&quot;, Type = typeof(RepeatButton))]
    [TemplatePart(Name = &quot;PART_TextBox&quot;, Type = typeof(TextBox))]
    public class DomainUpDown : Control
    {
        #region Fields
        private int _selectedIndex;
        private RepeatButton _upBuppton;
        private RepeatButton _downButton;
        #endregion

        #region Dependency properties
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register(&quot;Value&quot;, typeof (object), typeof (DomainUpDown), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged));

        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register(&quot;Items&quot;, typeof(IEnumerable), typeof(DomainUpDown), new PropertyMetadata(OnItemsChanged));
        #endregion

        /// <summary>
        /// Initializes the <see cref="DomainUpDown" /> class.
        /// </summary>
        static DomainUpDown()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DomainUpDown), new FrameworkPropertyMetadata(typeof(DomainUpDown)));
            BorderBrushProperty.OverrideMetadata(typeof(DomainUpDown), new FrameworkPropertyMetadata(SystemColors.ControlLightBrush));
        }

        /// <summary>
        /// Gets or sets the selected value.
        /// </summary>
        /// <value>The value.</value>
        public object Value
        {
            get { return GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        /// <summary>
        /// Gets or sets the items.
        /// </summary>
        /// <value>The items.</value>
        public IEnumerable Items
        {
            get { return GetValue(ItemsProperty) as IEnumerable; }
            set { SetValue(ItemsProperty, value);}
        }

        /// <summary>
        /// Gets or sets the index of the selected value.
        /// </summary>
        /// <value>The index of the selected.</value>
        protected int SelectedIndex
        {
            get { return _selectedIndex; }
            set
            {
                if (_selectedIndex == value)
                    return;

                _selectedIndex = value;

                Value = Items.Cast<object>().Skip(SelectedIndex).First();
            }
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            base.OnPreviewKeyDown(e);

            if (e.Key == Key.Down)
            {
                if (_downButton != null)
                    _downButton.Focus();

                OnDown(this, null);
                e.Handled = true;
            }

            if (e.Key == Key.Up)
            {
                if (_upBuppton != null)
                    _upBuppton.Focus();

                OnUp(this, null);
                e.Handled = true;
            }
        }

        /// <summary>
        /// When overridden in a derived class, is invoked whenever application code or internal processes call 
        /// <see cref="M:System.Windows.FrameworkElement.ApplyTemplate"/>.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (_upBuppton != null)
                _upBuppton.Click -= OnUp;

            if (_downButton != null)
                _downButton.Click -= OnDown;

            // Get the parts and attach event handlers to them
            _upBuppton = GetTemplateChild("PART_UpButton") as RepeatButton;
            _downButton = GetTemplateChild("PART_DownButton") as RepeatButton;

            if (_upBuppton != null)
                _upBuppton.Click += OnUp;

            if (_downButton != null)
                _downButton.Click += OnDown;
        }

        /// <summary>
        /// Invoked whenever an unhandled <see cref="E:System.Windows.UIElement.GotFocus"/> event reaches this element in its route.
        /// </summary>
        /// <param name="e">The <see cref="T:System.Windows.RoutedEventArgs"/> that contains the event data.</param>
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);

            // Move focus immediately to the buttons
            if (_upBuppton != null)
                _upBuppton.Focus();
        }

        private void OnUp(object sender, RoutedEventArgs routedEventArgs)
        {
            if (SelectedIndex > 0)
                SelectedIndex--;
        }

        private void OnDown(object sender, RoutedEventArgs routedEventArgs)
        {
            if (Items != null && SelectedIndex < Items.Cast<object>().Count() - 1)
                SelectedIndex++;
        }

        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var updown = d as DomainUpDown;
            SynchroniseValueWithIndex(updown, e.NewValue);
        }


        private static void OnItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var updown = d as DomainUpDown;
            SynchroniseValueWithIndex(updown, updown == null? null : updown.Value);
        }

        private static void SynchroniseValueWithIndex(DomainUpDown updown, object newValue)
        {
            if (updown == null || updown.Items == null)
                return;

            int i = 0;

            foreach (var element in updown.Items)
            {
                if (element.Equals(newValue))
                {
                    updown.SelectedIndex = i;
                    break;
                }

                i++;
            }
        }    
    }
}
September 30 2010
Older Posts