private static object Attach(
            FrameworkElement element,
            Func <object> viewModelFactory,
            ref bool attached,
            ref bool attaching,
            out IViewModel attachment)
        {
            Contract.Requires(element != null);
            Contract.Requires(viewModelFactory != null);
            Contract.Requires(!attached);
            Contract.Ensures(Contract.ValueAtReturn(out attached));

            object viewModel;

            attaching = true;

            try
            {
                viewModel = viewModelFactory();

                element.DataContext = viewModel;

                attachment = viewModel as IViewModel;

                if (attachment != null)
                {
                    if (attachment.IsAttached)
                    {
                        attachment.Detach();
                    }

                    attachment.Attach(element);
                }
            }
            finally
            {
                attaching = false;
            }

            attached = true;

            return(viewModel);
        }