Malte
Malte

Reputation: 13

Mahapps & Prism HamburgerMenu

i am currently building an WPF-App with Prism and Mahapps.

I ran into a Problem while implementing an HamburgerMenu with Prism. Is there a way to fill the HamburgerMenu via the Region?

As an example, when i use an control derived from an ItemsControls with an region attached to it (via the attached property RegionManager.RegionName), it will automatically fill any registered view to this region into the ItemsControls.

Is there an way to mimic this behavior for the HamurgerMenu?

Regards

Upvotes: 1

Views: 1838

Answers (1)

Andy Reed
Andy Reed

Reputation: 295

This is how I managed it.

1) Name a region for the menu items collection.

<controls:HamburgerMenu.ItemsSource>
            <controls:HamburgerMenuItemCollection prism:RegionManager.RegionName="MenuRegion"/>
</controls:HamburgerMenu.ItemsSource>

2) Define a region adapter for the HamburgerMenuItemCollection

public class HamburgerMenuItemCollectionRegionAdapter : RegionAdapterBase<HamburgerMenuItemCollection>

{
    public HamburgerMenuItemCollectionRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
        : base(regionBehaviorFactory)
    {
    }

    protected override void Adapt(IRegion region, HamburgerMenuItemCollection regionTarget)
    {
        region.Views.CollectionChanged += (s, e) =>
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (HamburgerMenuGlyphItem element in e.NewItems)
                {
                    regionTarget.Add(element);
                }
            }
        };
    }

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

3) Register the adapter in the bootstrapper.

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
    RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();
    mappings.RegisterMapping(typeof(HamburgerMenuItemCollection), Container.Resolve<HamburgerMenuItemCollectionRegionAdapter>());
    return mappings;
}

4) Define menu item in Prism module

public partial class OptionOneMenuItem : HamburgerMenuGlyphItem
{
    public OptionOneMenuItem()
    {
        Glyph = "/Assets/OptionOne.png";
        Label = "Option One";
        Command = ApplicationCommands.NavigateCommand;
        CommandParameter = typeof(OptionOnePageView);

        InitializeComponent();
    }
}

5) Finally register menu items in module initialsation.

protected override void InitializeModule()
{
    RegionManager.RegisterViewWithRegion("MenuRegion", typeof(MyOptionOneMenuItem));
    RegionManager.RegisterViewWithRegion("MenuRegion", typeof(MyOptionTwoMenuItem));
}

Upvotes: 3

Related Questions