MahApps HamburgerMenu and Caliburn Micro

MahApps is probably one of the most used UI library among WPF developers, with a galaxy of great controls. Despite that, recently I was surprised to see lack of proper example for Hamburger Menu control, particulary MVVM based. I was also more keen to know how to make best use of capabilities of Caliburn Micro along the way.

Here is how I ended up achieving my objectives.

XAML : Control, Content, ItemTemplate and HeaderTemplate

The first step would be to define the Control in Xaml, along with desired ContendTemplate,ItemTemplate and HeaderTemplate.

<mah:HamburgerMenu x:Name="Menu" DisplayMode="CompactOverlay" SelectedItem="{Binding ActiveItem,Converter={StaticResource SelectedItemConverter}}"
           ItemsSource="{Binding MenuItems,Converter={StaticResource MenuConverter}}"
           cal:Message.Attach="[Event ItemClick]=[Action MenuSelectionChanged($source,$eventArgs)]"
           HamburgerMenuHeaderTemplate="{StaticResource MenuHeaderTemplate}"
           ItemTemplate="{StaticResource MenuItemTemplate}">
    <mah:HamburgerMenu.Content>
       <ContentControl Grid.Column="0" Grid.Row="1" x:Name="ActiveItem" />
    </mah:HamburgerMenu.Content>
</mah:HamburgerMenu>

As you would have noticed couple of converters in here. We will get to that in a moment, but first let us define our MenuItemTemplate and MenuHeaderTemplate.

<!-- Menu Header Template -->
<DataTemplate x:Key="MenuHeaderTemplate">
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"  FontSize="16"  Foreground="White"  Text="Sample App" />
</DataTemplate>

<!-- Menu Item Template -->
<DataTemplate x:Key="MenuItemTemplate">
    <Grid x:Name="RootGrid" Height="48" Background="Transparent">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="48" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ContentControl Grid.Column="0"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Content="{Binding Icon}"
            Focusable="False" />
        <TextBlock Grid.Column="1"
           VerticalAlignment="Center"
           FontSize="16"
           Text="{Binding Label}" />
    </Grid>
</DataTemplate>

At this point, we need to create our ViewModels for each of the menu items. As we notice from the templates above, there are couple of fields which are required for each of Menu Items – a Title, and a Icon (_Icon is not quite mandatory, depending on the type of Menu Item you are creating).

Destination ViewModels

Let us go ahead and define our ViewModels for Menu Items.

public class PageViewModelBase : Screen
{
    public virtual string Title { get; }
    public virtual object Icon { get; }
}
public class HomePageViewModel : PageViewModelBase
{
    public override string Title => "Home";
    public override object Icon => new PackIconMaterial { Kind = PackIconMaterialKind.Home };
}
public class ProfilePageViewModel : PageViewModelBase
{
    public override string Title => "Profile";
    public override object Icon => new PackIconMaterial { Kind = PackIconMaterialKind.AccountStar };
}

In the above example, we are using the MahApps.Metro.IconPack for Icons, but that is only an implementation detail which could can easily vary. For sake of simplicity, I have omitted the Views here, but that could be found in the example solution given in the end of this article.

The Glue : ValueConverters and ActiveItem

We now have different ViewModels defined, and it is time to create the dynamic collection to bind to our HamburgerMenu Control. So, in our ShellViewModel, we will do the following.

public ShellViewModel()
{
    MenuItems = new List<PageViewModelBase>
    {
        new HomePageViewModel(),
        new ProfilePageViewModel()
    };
}

public IEnumerable<PageViewModelBase> MenuItems { get; }

We are almost there, and now as the final step, we need to write our converters. There are two converters involved,

  • PageToMenuItemConverter – Converts from ViewModel Collection to HamburgerMenuIconItem.
  • SelectedItemConverter – Parse the ViewModel from SelectedItem
public class PageToMenuItemConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<PageViewModelBase> nmItemCollection)
        {
            return nmItemCollection.Select(item => new HamburgerMenuIconItem
            {
                Tag = item,
                Icon = item.Icon,
                Label = item.Title
            });
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class SelectedItemConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value is HamburgerMenuIconItem menuItem ? menuItem.Tag : value;
    }
}

That’s all we need. Your menu would be up and running now. You can find the example code in my Github here

Caliburn.Micro Template Pack now supports VS 2019

So glad to announce that Caliburn.Micro Template Pack now supports Visual Studio 2019.

Caliburn.Micro Template Pack for WPF contains a comprehensive collection of Project Templates and Code Snippets for developing WPF application using Caliburn.Micro. It also includes Bootstrap templates for SimpleContainer, MEF and Unity.

You can download the template from Visual Studio Marketplace

You can read more on the template here

Caliburn.Micro #008: Gesture Recognition using Short-Hand Syntax

In this part of Caliburn.Micro tutorials we would explore how to configure and use Gesture Recognition with Caliburn.Micro, particularly exploiting the Short-Hand syntax for Actions. Caliburn.Micro doesn’t support this out of the box, so obviously we need to work around the Actions to provide support for Gestures. Let’s first formulate the syntax of how we would like to add a Gesture and its binding in XAML and then find our way to it.

We would ideally like to use a syntax, that is close to Action Syntax for triggering events.

[Event Click]=[Action Method1] // Normal Events
[Key F12]=[Action Method1] // Ideal Gesture Syntax.

The first step required would be to write a Trigger that would catch the KeyPress event. The trigger should provide ability to pass the expected “Key” and invoke the binded action when the expected “Key” is pressed. Let’s go ahead and write the required Custom Trigger.

public class KeyTrigger : TriggerBase<UIElement>
{
public static readonly DependencyProperty KeyProperty =
DependencyProperty.Register("Key", typeof(Key), typeof(KeyTrigger), null);

public Key Key
{
get => (Key)GetValue(KeyProperty);
set => SetValue(KeyProperty, value);
}

protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyDown += OnAssociatedObjectKeyDown;
}

protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyDown -= OnAssociatedObjectKeyDown;
}

private void OnAssociatedObjectKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key)
{
InvokeActions(e);
}
}
}

The KeyTrigger is quite self-explainatory. It declares Dependency Property called “Key” of System.Windows.Input.Key, and verifies if the Key Pressed is actually the one registered in KeyDown Event of AssociatedObject. If the Key matches the registered Key, it invokes the associated Action.

The Step is to Write our Custom Action Format, that would be recognized by the Caliburn.Micro Parser, and calls from Trigger(and there by Action). In order to achieve this, we re-define Parser.CreateTrigger method, which is responsible to generate the trigger. We do this in our Bootstrapper, overriding Configure Method.

// In Bootstrapper

protected override void Configure()
{
var defaultCreateTrigger = Parser.CreateTrigger;

Parser.CreateTrigger = (target, triggerText) =>
{
if (string.IsNullOrEmpty(triggerText)) return defaultCreateTrigger(target, null);

var regex = new Regex($@"^\[(?<{X_ACTION}>[a-zA-Z]+)\s(?<{X_SHORTCUT}>[a-zA-Z0-9]+)\]$");
var matches = regex.Match(triggerText.Trim());

switch (matches.Groups[X_ACTION].Value.ToUpper())
{
case X_KEY:
return new KeyTrigger
{
Key = (Key)Enum.Parse(typeof(Key), matches.Groups[X_SHORTCUT].Value, true),
};
default:
return defaultCreateTrigger(target, triggerText); ;
}
};
}

As observed, we check if the triggerText contains our special keywords, and if so, create our Custom trigger, namely KeyTrigger. In all other case, it returns the default trigger.

That’s all we require to configure our Gesture Recognition. We can now move on to our View and define the Gesture using our custom Action syntax.

cal:Message.Attach="[Key Enter] = [Action Increment]"

You can access the complete code sample, demonstrated in this post in my Github.

Btw, Merry Christmas !!!

Verifying if View Exists for specified ViewModel

There might raise situations in your Project where you might be interested to check if the ViewModel specified has a corresponding View defined and gradefully handle the error, than throwing an exception.

Caliburn Micro’s ViewLocator class provides you methods that enables you to do exactly that.

if ((ViewLocator.LocateForModelType(typeof(DummyViewModel), null, null) is TextBlock tb
&& tb.Text.StartsWith("Cannot find", StringComparison.InvariantCultureIgnoreCase)))
{
// View does not exist, Terminate or redirect to another
}
else
{
// View found, redirect to intended one
}

Caliburn.Micro #007 : Bootstrapper with Unity

Unity is one of the most commonly used IOC containers used by developers, and it would be unfair if I don’t include it as a part of the Caliburn.Micro WPF Tutorials (Creating Bootstrappers).  This particular post is dedicated to building bootstrapper for Caliburn.Micro application using Unity as the IoC Container.


The key for creating Bootstrappers for Caliburn.Micro application lies in overriding 4 methods from the BootstrapperBase class. The 4 methods are
  1. Configure
  2. BuildUp
  3. GetInstance
  4. GetAllInstance
The implementation using SimpleContainer and MEF is described in the earlier parts of the Caliburn.Micro Tutorials. Let’s go ahead and implement the Configure method using Unity.
private IUnityContainer _unityContainer;
protected override void Configure()
{
    _unityContainer = new UnityContainer();
    _unityContainer.RegisterInstance<IWindowManager>(new WindowManager());
    _unityContainer.RegisterInstance<IEventAggregator>(new EventAggregator(), new ContainerControlledLifetimeManager());
    //  View Models
    _unityContainer.RegisterInstance<IShellViewModel>(new ShellViewModel());
}
Container using Unity is initialized using the UnityContainer class. RegisterInstance methods are used to register your Classes. For cases, where you need Singletons, you can make use of the ContainerControlledLifeTimeManager as seen in the above example. This place will also hold your ViewModel registrations as well.


Rest of the 3 methods are pretty simple and straightforward to understand.
protected override void BuildUp(object instance)
{
  _unityContainer.BuildUp(instance);
  base.BuildUp(instance);
}
protected override object GetInstance(Type service, string key)
{
  return string.IsNullOrEmpty(key) ? _unityContainer.Resolve(service, key) : _unityContainer.Resolve(service);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
  return _unityContainer.ResolveAll(service);
}
Finally, similar to earlier Bootstrappers, we use the OnStartup Method to invoke the ShellViewModel.

protected override void OnStartup(object sender, StartupEventArgs e)
{
   DisplayRootViewFor<IShellViewModel>();
}

The complete code sample can be accessed at my Github. The bootstrapper template is also included as a part of Caliburn.Micro Template Pack for WPF.

Caliburn.Micro #006 : Event Aggregators & Window Managers

Consider the classic scenario when you need to show the currently logged in User Name in your main Window, once you have successfully logged in. The The login Window is supposed to be a Modal Dialog, and isn’t remotely aware of the Label displaying Username in the Main Window.

WPF handles Modal Dialogs and messaging service between Views using Window Managers and Event Aggregators.

Event Aggregators allows a loosely coupled message parsing mechanism between different View Models in the system. As the Caliburn Micro Documentation states, an Event Aggregator is a service that provides the ability to publish an object from one entity to another in a loosely based fashion.

Let’s being by creating our Sample Application using the Caliburn.Micro Template Pack, which makes it easier to kick start a Caliburn.Micro based application. The complete sample code described in this post is available in Github.
Capture

 

We would be using MEF as our IoC Container. So let’s make changes to Bootstrapper to accommodate MEF. For sake of ease, we will remove the existing Bootstrapper and add MEF Template supplied along with the Caliburn.Micro Template Pack.

 

Capture1
We will now our Contract Interface and the required LoginView as well as our MainWindow (we will it ShellView). The skeleton of code looks like following now.
ShellView.Xaml
 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
        
        <StackPanel Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Label x:Name="UserName" FontWeight="Bold" FontSize="32"></Label>
        </StackPanel>
        
        <StackPanel Grid.Row="1" Margin="10,10,10,10">
            <Button Margin="5,5,5,5" cal:Message.Attach="[Event Click]=[Action PromptForLogin]">Login</Button>
        </StackPanel>
    </Grid> 

IShell Interface

    public interface IShell
    {

    }

ShellViewModel

  [Export(typeof(IShell))]
    public class ShellViewModel : PropertyChangedBase, IShell
    {
        private string _userName  = default;
        public string UserName
        {
            get => _userName;
            set
            {
                _userName = value;
                NotifyOfPropertyChange(nameof(UserName));
            }
        }

        public void PromptForLogin() {};

    }
We will add the skeleton code for Login Window as well before adding the code to invoke it as a separate Window (not Content Control).
LoginView.Xaml
 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>
        
        <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="Lavender">
            <Label>User Login</Label>
        </StackPanel>
        <TextBox Margin="5,5,5,5" Grid.Row="1" Name="UserName">UserName</TextBox>
        <TextBox Margin="5,5,5,5" Grid.Row="2" Name="Password">Password</TextBox>
        <Button Grid.Row="3" Margin="5,5,5,5" cal:Message.Attach="[Event Click]=[Action Validate(UserName,Password)]">Login</Button>
    </Grid>

ILogin Interface

public interface ILogin
{
    bool Validate(string userName, string passWord);
}

LoginViewModel

[Export(typeof(ILogin))]
public class LoginViewModel : ILogin
{
    // Since this is a demo, we will always return true
    public bool Validate(string userName, string passWord) => true;

}

Alright, so we have our barebone code ready. Time to link up the chain. The first task is to ensure we have ShellView as our primary start up Window, which we set by altering the code in our Bootstrapper.

protected override void OnStartup(object sender, StartupEventArgs e)
{
    DisplayRootViewFor();
}

The next task is to ensure the Login Window User Clicks Login Button. We do this by utilizing the Window Manager, which is injected (via Dependency Injection) into ShellViewModel. We will add a constructor for ShellViewModel decorated with the ImportingConstructor Attribute. We will also inject LoginViewModel as well in to the class. We will then use the WindowManager for invoking the LoginViewModel as a Modal Dialog. Our constructor and PromptForLogin Method looks like following now.

[ImportingConstructor]
public ShellViewModel(IWindowManager windowManager,ILogin loginWindow)
{

}

public void PromptForLogin() => _windowManager.ShowDialog(_loginWindow);

This opens up the Login Window for you. All good till now, the Login Window is displayed, and you type in the UserName & Password, and Click the Login button to invoke the Validate Method. But how do you pass the UserName information to the ShellViewModel ? This is where Event Aggregator comes into place.

Event Aggregators allows ViewModels to pass (broadcast) information (in a model) to any other View Models who has subscribed to the event. We will begin by creating the model which would contain the information that will passed along Event Aggregators.

public class UserInfoModel
{
     public string UserName { get; set; }
}

We will then inject an instance of EventAggregator in the LoginViewModel. We will also modify our Validate Method a bit. The LoginViewModel class now looks like following.

[Export(typeof(ILogin))]
public class LoginViewModel : ILogin
{
private IEventAggregator _eventAggregator;

[ImportingConstructor]
public LoginViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator = eventAggregator;
    _eventAggregator.Subscribe(this);
}

// Since this is a demo, we will always return true
public bool Validate(string userName, string passWord)
{
    _eventAggregator.PublishOnUIThread(new UserInfoModel(){UserName = userName});
    return true;
}
}

As you can see, we have used the PublishOnUIThread Method of Event Aggregator to publish the UserInfoModel object to anyone listening. We will now move to our ShellViewModel and ensure the class is listening. We would also see how we access the message send by the Login View Model.

Let’s begin by modifying the ShellViewModel to inject the EventAggregator to ShellViewModel, Our constructor now looks as following.

[ImportingConstructor]
public ShellViewModel(IWindowManager windowManager,ILogin loginWindow, IEventAggregator eventAggregator)
{
    eventAggregator.Subscribe(this);
    windowManager.ShowDialog(loginWindow);
}

Now comes the most important part, we need to implement the IHandle interface, where T is the model of the event object, which in our case is UserInfoModel. The interface contains a single method Handle, which we implement soon. Prior to that, this is how our class declaration looks now.

public class ShellViewModel : PropertyChangedBase, IShell, IHandle

The Handle Method of IHandle Interface looks like following.

public void Handle(UserInfoModel message)
{
this.UserName = message.UserName;
}

As you can see, we have assigned the UserName property of ViewModel from the message passed by the EventAggregator. That’s all we need to do. The EventAggregator has passed the message to all subscribers in the message bus for that particular event model. We then capture the message by implementing the Handle Method in IHandle interface.

Caliburn.Micro

Caliburn.Micro is a extremely lightweight MVVM Framework. This series provides an introduction/refresher to developing WPF applications with Caliburn.Micro
1. Caliburn.Micro: Introduction
2. Caliburn.Micro: Bindable Collections & Events
3. Caliburn.Micro: Events (Short Hand Syntax)
4. Caliburn.Micro:Bootstrapper with SimpleContainer
5. Caliburn.Micro: Bootstrapper with MEF
6. Caliburn.Micro: Event Aggregators & Window Managers
7. Caliburn.Micro: Bootstrapper with Unity
8. Caliburn.Micro: Gesture Recognition using Short-Hand Syntax

 

Caliburn.Micro Template Pack

Reworked on the Caliburn.Micro Template Pack recently. Thought it was necessary to provide the developers the ability to Create Bootstrapper as an Item Template. It also provides the option to develop the Pack more in coming days. You can access the Template Pack from Marketplace using the link here. Details of the pack is as follows.

Caliburn.Micro Template Pack for WPF

Caliburn.Micro Template Pack for WPF contains a comprehensive collection of Project Templates and Code Snippets for developing WPF application using Caliburn.Micro

Project Templates

  •  WPF Application that utilizes Caliburn.Micro for MVVM Framework

Item Templates

  •  Bootstrapper Class with MEF as IoC
  •  Bootstrapper Class with SimpleContainer as IoC

Code Snippets

  • propcm – Creates Property with NotifyOfPropertyChange and backing field
  • funcm – Creates function with Guard methods

 

Caliburn.Micro #005 : Bootstrapper with MEF

Previously, we learnt how to use SimpleContainer to set up our IoC Containers. We would be now looking into making the application more loosely coupled by leveraging the MEF. Just like with SimpleContainer, we would be focusing on the basic steps while configuring the IoC – Registering the IoC Container with Caliburn Micro and then registering the Service bindings. Let’s go ahead override the necessary methods

private CompositionContainer _Container;

protected override object GetInstance(Type service, string key)
{
  string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
  var exports = _Container.GetExportedValues(contract);
  if (exports.Any())
      return exports.First();
  else
      throw new Exception("Could not find the key");
}

protected override void BuildUp(object instance)
{
  _Container.SatisfyImportsOnce(instance);
}

protected override IEnumerable GetAllInstances(Type service)
{
  return _Container.GetExportedValues(AttributedModelServices.GetContractName(service));
}

We will now go ahead and register our Service Bindings. This is where things get interesting.

protected override void Configure()
{
  _Container = new CompositionContainer(
                new AggregateCatalog(AssemblySource.Instance.Select(x=> new AssemblyCatalog(x)).OfType())
                );
  var batch = new CompositionBatch();
  batch.AddExportedValue(new WindowManager());
  batch.AddExportedValue(new EventAggregator());
  batch.AddExportedValue(_Container);

  _Container.Compose(batch);
}

As seen in the code above, we are using the AssemblySource to parse the ViewModels in the Assembly.

That’s it in Bootstrapper, but do not forget to decorate your View Model class with [Export()] Attribute and Constructor with [ImportingConstructor]. (For injecting dependency)

[Export(typeof(IReport))]
public class ReportViewModel :Screen, IReport
{
  [ImportingConstructor]
  publicReportViewModel(IEventAggregator EventAggregator)
  {
    // Do Constructor tasks
  }
}

We will delve into EventAggregators later, but for the moment, consider it an example of how to inject a dependency in the constructor when working with MEF.

Code sample for this post can be found here. The complete list of tutorials on Caliburn.Micro can be accessed here

 

Caliburn.Micro #004 : Bootstrapper with SimpleContainer

Let’s take a step back and look into our Bootstrapper in detail now. The first version of Bootstrapper we declared earlier is a rather simple one, without utilizing the some of the functionalities which takes Caliburn.Micro, or for that matter, any MVVM Framework ahead. The implementation of IoC Container.
We would be concentrating into two different IoC Containers – a Caliburn.Micro in-build container called SimpleContainer and the MEF (Microsoft Extensibility Framework) based Container. In this first part, we would be concentrating on the SimpleContainer. Let’s begin by declaring the interface contract for our Shell View Model.
  public interface IShell
  {

  }
I would leave the implementation of ShellViewModel and ShellView to the discretion of the reader, considering that is not what we are focusing on this particular session. We would instead focus on the Bootstrapper Class and how we would be triggering the ShellViewModel from it by utilizing the IoC container. We would however, write our OnStartup method, triggering the ShellViewModel through the IShell interface.
protected override void OnStartup(object sender, StartupEventArgs e)
{
  this.DisplayRootViewFor();
}
SimpleContainer
The first step is to configure the container with the Caliburn Micro Framework. We accomplish this by overriding 3 methods, the GetInstance, GetAllInstances and BuildUp.
private SimpleContainer _Container = new SimpleContainer();

protected override object GetInstance(Type service, string key)
{
  return _Container.GetInstance(service, key);
}

protected override IEnumerable GetAllInstances(Type service)
{
  return _Container.GetAllInstances(service);
}

protected override void BuildUp(object instance)
{
  _Container.BuildUp(instance);
}
Service Binding
Most of the code above are self explanatory. Having registered/configured your IoC Container with the framework, the next task is to register your contracts. We do this by overriding the Configure Method.
protected override void Configure()
{
  _Container.Instance(new WindowManager());
  _Container.Singleton();
  _Container.PerRequest();
}
Notice the three different methods we have used to register the service bindings. The Instance Method registers a pre-constructed instance with the type. This is similar to the Singleton method, however with a significant difference. The instance of Instance Method is pre-constructed while for the Singleton Method registration, the instance of Type is created only when first requested.
That’s it, the IoC container would now do the magic for us, by resolving the contracts when required.
There is another approach (method) to register the Service Binding, which focuses on auto-resolution of the Type by scanning the assembly for any implementation of the particular contract. For example, if we need to replace the service binding of IShell with assembly inspection, we would do the following.
 _Container.AllTypesOf(Assembly.GetExecutingAssembly());
In the next part of Caliburn.Micro Tutorial, we will look into implementing the IoC container with the more advanced, MEF based IoC Containers.
Sample code for this section can be found here. For complete list of tutorials on Caliburn.Micro, please follow this link