ToolBarTray Adapter

There isn’t a native ToolBarTray adaptor built into the Prism library. Creating an adapter is only a matter of learning the secret handshake.

It takes three parts to get an adaptor to work. The first part is the adaptor itself. The second is wiring it into the bootstrapper. The third part is the XAML to define the region. Below are samples of all three.

Adaptor Code:

[Export]
public class ToolBarTrayRegionAdaptor : RegionAdapterBase<ToolBarTray>
{
  [ImportingConstructor]
  public ToolBarTrayRegionAdaptor(IRegionBehaviorFactory regionBehaviorFactory)
    : base(regionBehaviorFactory)
  {
  }

  protected override IRegion CreateRegion()
  {
    return new AllActiveRegion();
  }

  protected override void Adapt(IRegion region, ToolBarTray regionTarget)
  {
    region.Views.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
    {
      OnViewsCollectionChanged(regionTarget, e);
    };
  }

  private void OnViewsCollectionChanged(ToolBarTray regionTarget, NotifyCollectionChangedEventArgs e)
  {
    switch ( e.Action )
    {
      case NotifyCollectionChangedAction.Add:
        foreach ( var toolBar in e.NewItems.OfType<ToolBar>().Where(i => i != null) )
          regionTarget.ToolBars.Add(toolBar);
        break;
      case NotifyCollectionChangedAction.Remove:
        foreach ( var toolBar in e.NewItems.OfType<ToolBar>().Where(i => i != null) )
          regionTarget.ToolBars.Remove(toolBar);
        break;
    }
  }
}

Bootstrapper Code:

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
  var regionAdapterMappings = base.ConfigureRegionAdapterMappings();
  regionAdapterMappings.RegisterMapping(typeof(ToolBarTray), Container.GetExportedValue&lt;ToolBarTrayRegionAdaptor&gt;());
  return regionAdapterMappings;
}

XAML Code:

<ToolBarTray regions:RegionManager.RegionName="{x:Static ux:RegionName.COMMAND_REGION}" />

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.