Source

Presentations / Composite WPF / Samples / Entico.Shared / Infrastructure / Regions / AvalonPaneRegion.cs

paulstovell 32af711 


































































using System.Linq;
using System.Windows.Data;
using AvalonDock;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;
using System.Windows;

namespace Entico.Shared.Infrastructure.Regions
{
    public class AvalonPaneRegion : Region
    {
        private readonly Pane _pane;

        public AvalonPaneRegion(Pane pane, string name)
        {
            _pane = pane;
            Name = name;
        }

        public override void Activate(object view)
        {
            var wrapped = UnwrapExistingView(view);
            wrapped.Focus();
            base.Activate(view);
        }

        public override IRegionManager Add(object view, string viewName, bool createRegionManagerScope)
        {
            var result = base.Add(view, viewName, createRegionManagerScope);
            var wrapper = WrapViewIfNotAlreadyWrapped(view);
            if (!_pane.Items.Contains(wrapper))
                _pane.Items.Add(wrapper);
            return result;
        }

        public override void Remove(object view)
        {
            var wrapped = UnwrapExistingView(view);
            _pane.Items.Remove(wrapped);
            base.Remove(view);
        }

        private DockableContent UnwrapExistingView(object view)
        {
            if (view is DockableContent)
            {
                return (DockableContent) view;
            }
            return _pane.Items.OfType<DockableContent>().FirstOrDefault(x => x.Content == view);
        }

        private DockableContent WrapViewIfNotAlreadyWrapped(object view)
        {
            if (view is DockableContent)
            {
                return (DockableContent)view;
            }
            var wrapped = UnwrapExistingView(view);
            if (wrapped == null)
            {
                wrapped = new DockableContent();
                wrapped.Content = view;
                BindingOperations.SetBinding(wrapped, ManagedContent.TitleProperty, new Binding("Title") {Source = view});
            }
            return wrapped;
        }
    }
}