Fody and “OnPropertyChanged” – The Unusual behavior

As a WPF Developer, Fody has been an extremely vital component in my aresenal. It takes a lot of burden off me by injecting some of the boiler plate codes. Despite that, there is one unusually behavior of Fody, which I have difficulty in digesting.

For demonstration, let us create an example View for ourselves. For the sake of example here, am relying on Caliburn Micro for my MVVM.

<StackPanel>
    <TextBlock Text="{Binding RandomNumber}" FontSize="16" HorizontalAlignment="Center"/>
    <Button Content="Randomize" x:Name="Randomize"/>
</StackPanel>

The ViewModel, at the moment, looks like the following.

public class ShellViewModel:Screen
{
    private Random _random;

    public ShellViewModel()
    {
        _random = new Random();
    }
    public long RandomNumber { get; set; }

    public void Randomize()
    {
        RandomNumber = _random.Next();
    }
}

This works perfectly fine. If you examine the code via ILSpy, you could notice that Fody has injected the code correctly as one would expect.

public class ShellViewModel : Screen
{
	private Random _random;

	public long RandomNumber
	{
		[CompilerGenerated]
		get
		{
			return <RandomNumber>k__BackingField;
		}
		[CompilerGenerated]
		set
		{
			if (<RandomNumber>k__BackingField != value)
			{
				<RandomNumber>k__BackingField = value;
				OnPropertyChanged(<>PropertyChangedEventArgs.RandomNumber);
			}
		}
	}


	public ShellViewModel()
	{
		_random = new Random();
	}

	public void Randomize()
	{
		RandomNumber = _random.Next();
	}
}

The OnPropertyChanged call here points to the PropertyChangedBase.OnPropertyChanged method of Caliburn Micro (PropertyChangedBase implements INotifyPropertyChanged in Caliburn Micro)

protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
	this.PropertyChanged?.Invoke(this, e);
}

Let us add some more code to our ViewModel and see how Fody behaves. Assume that we need to do some special handling when the Property Changed event is triggered in our ViewModel. So we will go ahead and subscribe in our constructor.

public ShellViewModel()
{
    _random = new Random();
    PropertyChanged += HandlePropertyChanged;
}

private void HandlePropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    // Do something here
}

Fody, quite expectedly, handles the change gracefully.

public class ShellViewModel : Screen
{
	private Random _random;

	public long RandomNumber
	{
		[CompilerGenerated]
		get
		{
			return <RandomNumber>k__BackingField;
		}
		[CompilerGenerated]
		set
		{
			if (<RandomNumber>k__BackingField != value)
			{
				<RandomNumber>k__BackingField = value;
				OnPropertyChanged(<>PropertyChangedEventArgs.RandomNumber);
			}
		}
	}

	public ShellViewModel()
	{
		_random = new Random();
		PropertyChanged += HandlePropertyChanged;
	}

	private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
	{
	}

	public void Randomize()
	{
		RandomNumber = _random.Next();
	}
}

So far, so good. This is exactly like one would expect. The injected code still calls the INotifyPropertyChanged implementation(in our base class).

set
{
    if (<RandomNumber>k__BackingField != value)
    {
        <RandomNumber>k__BackingField = value;
        OnPropertyChanged(<>PropertyChangedEventArgs.RandomNumber);
    }
}


But this is also where things start to behave strangely (one could counter argue this, but i still feel the following behavior is strange). Let us rename our PropertyChanged event handler as HandlePropertyChanged.

public ShellViewModel()
{
    _random = new Random();
    PropertyChanged += OnPropertyChanged;
}

private void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    // Do something here
}

Let us examine the code generated by Fody now.

public long RandomNumber
{
    [CompilerGenerated]
    get
    {
        return <RandomNumber>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        if (<RandomNumber>k__BackingField != value)
        {
            <RandomNumber>k__BackingField = value;
            OnPropertyChanged(this, <>PropertyChangedEventArgs.RandomNumber);
        }
    }
}

public ShellViewModel()
{
    _random = new Random();
    PropertyChanged += OnPropertyChanged;
}

private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
}

The code injected by Fody has changed now and instead of calling the implementation of INotifyPropertyChanged, it is invoking the Event Handler of PropertyChanged.

set
{
    if (<RandomNumber>k__BackingField != value)
    {
        <RandomNumber>k__BackingField = value;
        OnPropertyChanged(this, <>PropertyChangedEventArgs.RandomNumber);
    }
}

In a way, if one was to think about it, it is a good behavior. Fody, on sensing that we have subscribing to PropertyChanged handler, ensure we are calling the handler instead. But, then the behavior should have been same when the Handler name was HandlePropertyChanged.

The strange part, which am not comfortable with this, is that this call to Handler occurs only when the Handler is named OnPropertyChanged. In every other case the injected code points to the implementation of INotifyPropertyChanged. I would like to call this a bug – You could expect the behavior to be consistent.

One of the troubles with this behavior (other than the obvious inconsistency) is that is extremely hard to trace this issue (remember – Fody injects the code) unless one is aware of this strange naming convention followed by Fody. I hope Fody does something to correct, if not make the make the behavior more consistent.

View Model First Approach using Caliburn Micro

While it is possible to use both View Model First and View First approach while using Caliburn Micro, I personally feel one should stick to one single appraoch thoughout your application. Mixing the two approaches would impact the readability of code adversely.

View Model First Approach

In this post we will look at the ViewModel first approach, which is the default approach used by Caliburn Micro. Simply stated, it uses ViewModel to recognize the associated View.

Let us assume we have a ShellViewModel class, which contains an instance of UserProfileViewModel, defined as in example code below.

public class ShellViewModel:Conductor<object>
{
    public UserProfileViewModel UserProfile { get; set; }

    public ShellViewModel()
    {
        UserProfile = IoC.Get<UserProfileViewModel>();
        UserProfile.Name = "Anu Viswan";
        UserProfile.Age = 37;
    }
}

The Xaml part, particularly the View detection is quite simpler here, thanks to the Caliburn Micro’s conventions.

<ContentControl  x:Name="UserProfile"/>

The caliburn micro would detect the required View using the ViewLocator.LocateForModelType method. Following is how it looks like.

public static Func<Type, DependencyObject, object, UIElement> LocateForModelType = (modelType, displayLocation, context) =>{
    var viewTypeName = modelType.FullName.Replace("Model", string.Empty);
    if(context != null)
    {
        viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
        viewTypeName = viewTypeName + "." + context;
    }

    var viewType = (from assmebly in AssemblySource.Instance
                    from type in assmebly.GetExportedTypes()
                    where type.FullName == viewTypeName
                    select type).FirstOrDefault();

    return viewType == null
        ? new TextBlock { Text = string.Format("{0} not found.", viewTypeName) }
        : GetOrCreateViewType(viewType);
};

As you can observe, the method removes Model from the full name of the viewmodel to recognize the associate view. The parameter context brings us to an interesting scenario, which we will discuss a bit later. But for now, it becomes clear that how the naming conventions of Caliburn Micro works under the hood.

Custom naming conventions is easily possible with Caliburn Micro. But I guess that is another topic, which need’s a post of its own.

Binding to Collection of ViewModel

For now, let us look into another scenario. Let us assume, we have a collection of ViewModels which needs to be displayed in an ItemsControl.

public class ShellViewModel:Conductor<object>
{
    public IEnumerable<UserProfileViewModel> UserProfileCollection { get; set; }
    public ShellViewModel()
    {
        UserProfileCollection = Enumerable.Range(1, 10).Select(x => new UserProfileViewModel { Name = $"Sample Name {x}", Age = 37 + x });
    }
}

Binding the collection to ItemsControl and displaying each of the Items in a ContentControl would require a minor change. The usage of View.Model attached property, which is defined as

public static DependencyProperty ModelProperty =
            DependencyPropertyHelper.RegisterAttached(
                "Model",
                typeof(object),
                typeof(View),
                null,
                OnModelChanged
                );


public static void SetModel(DependencyObject d, object value) {
    d.SetValue(ModelProperty, value);
}

public static object GetModel(DependencyObject d) {
    return d.GetValue(ModelProperty);
}

static void OnModelChanged(DependencyObject targetLocation, DependencyPropertyChangedEventArgs args)
{
    if (args.OldValue == args.NewValue) {
        return;
    }

    if (args.NewValue != null) {
        var context = GetContext(targetLocation);

        var view = ViewLocator.LocateForModel(args.NewValue, targetLocation, context);
        ViewModelBinder.Bind(args.NewValue, view, context);
        if (!SetContentProperty(targetLocation, view)) {

            Log.Warn("SetContentProperty failed for ViewLocator.LocateForModel, falling back to LocateForModelType");

            view = ViewLocator.LocateForModelType(args.NewValue.GetType(), targetLocation, context);

            SetContentProperty(targetLocation, view);
        }
    }
    else {
        SetContentProperty(targetLocation, args.NewValue);
    }
}

As you can observe, the View.Model attached property, under the hood uses the ViewLocator.LocateForModel method itself, which we had previously seen.

We have now seen how View.Model is defined, so let us go ahead and write our xaml to finish off the example.

<ItemsControl x:Name="UserProfileCollection">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Grid.Row="1" BorderThickness="1" BorderBrush="LightGray">
                <ContentControl cal:View.Model="{Binding}"/>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The Context Parameter – Multiple Views for single View Model

We had skipped the Context Parameter for the ViewLocator.LocateForModel method earlier. Let us now examine the role of the parameter in detail.

var viewTypeName = modelType.FullName.Replace("Model", string.Empty);
if(context != null)
{
    viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
    viewTypeName = viewTypeName + "." + context;
}

From the above code (from the ViewLocator.LocateForModel), it is obvious that if the context parameter is non-null value, then it would replace the View string with a . followed by the context string. With that in mind, let us build our alternative views using the following folder structure.

Let us now pass the context parameter in our example above using the attached property.

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Border Grid.Row="1" BorderThickness="1" BorderBrush="LightGray">
            <ContentControl cal:View.Model="{Binding}" cal:View.Context="StudentProfile"/>
        </Border>
    </DataTemplate>
</ItemsControl.ItemTemplate>

The UserProfileView would be now replaced with StudentProfile view which we have created in the previous step.

Conclusion 

In this post, we examined how to name resolution happens behind the scene for Caliburn Micro in a View Model First approach. We will examine View First approach in a later post, but if you understand the difference between the approach, and the working of one, it becomes easier to expect the other should behave.

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.

Stimulsoft – Non-Modal Designer in WPF App, Part 2

In the previous post, we explored Supervising Controller Pattern to provide a solution to the issue we faced when using Stimulsoft Designer  Controller as an embedded control in WPF application. Even while we used the Supervising Controller Pattern, we still fiddled with the MVVM pattern by making the ViewModel “aware” of the View, even though it wasn’t depended. In this section, we would be exploring another method, through which could eliminate the ‘awareness’ factor, allowing us to work along the MVVM pattern with all its purity.
As in previous section, we will begin by adding the designer control in our XAML.
<wpfdesign:StiWpfDesignerControl></wpfdesign:StiWpfDesignerControl>
So how do we do resolve the issue this time around, without breaking the MVVM pattern ? Instead of Supervising Controller Pattern, we would instead on something which is native to the WPF. The Behaviours and Attached Properties
Behavior and Attached Property
Behavior allows us to Attach a new property the StiWpfDesignerControl, which is bindable.
public class ReportBehavior : Behavior
    {
        public static readonly DependencyProperty ReportSourceProperty = DependencyProperty.RegisterAttached("ReportSource", typeof(object), typeof(ReportBehavior), new PropertyMetadata(ReportSourceChanged));

        private static void ReportSourceChanged(DependencyObject DependencyObject, DependencyPropertyChangedEventArgs PropertyChangedEvent)
        {
            var stidesigner = DependencyObject as StiWpfDesignerControl;

            if (stidesigner != null)
                stidesigner.Report = PropertyChangedEvent.NewValue as Stimulsoft.Report.StiReport;
        }

        public static void SetReportSource(DependencyObject target, object value)
        {
            target.SetValue(ReportSourceProperty, value);
        }

        public static object GetReportSource(DependencyObject target)
        {
            return target.GetValue(ReportSourceProperty);
        }
As can be seen in the code above, we have defined a property called “ReportSource” which allows us to the set the Report Property of the Designer Controller.  We can now bind our property in our XAML
Putting it all together
      <wpfdesign:StiWpfDesignerControl local1:ReportBehavior.ReportSource="{Binding Path=ActiveReport}" x:Name="DesignerControl"  ></wpfdesign:StiWpfDesignerControl>
Don’t forget the namespace
xmlns:local1="clr-namespace:CM005.Behaviour"

 

Stimulsoft – Non-Modal Designer in WPF App

Stimulsoft Reports is one among the most powerful and easy to use Reporting Tools available. While this post is not focused on feature of Stimulsoft Reports, it is worth checking out the features in Stimulsoft Website.

 

Embedded Stimulsoft Designer Control and MVVM

The post would rather focus on displaying the powerful Stimulsoft Designer in a WPF application with Data Source being .Net Objects created at runtime. While this is pretty straightforward to do when you want to invoke the designer as a Modal Dialog, it becomes a little messier when you want the designer to be an embedded control, particularly when you want to stick to the MVVM Pattern.
Let’s first go ahead and place our designer control in the View first.
<wpfdesign:StiWpfDesignerControl></wpfdesign:StiWpfDesignerControl>

Don’t miss out adding the namespace

xmlns:wpfdesign="clr-namespace:Stimulsoft.Report.WpfDesign;assembly=Stimulsoft.Report.WpfDesign"

For sake of example, we would mock our business object rather than taking it out of Database

   public class Products
   {
       public string Name { get; set; }
       public decimal Price { get; set; }
   }

var   _ProductCollection = new List()
  {
  new ProductModel() { Name = "Product 1", Price = 100 },
  new ProductModel() { Name = "Product 2", Price = 200 }
  };

We do have a property ‘ActiveReport’ , which holds the report details and is responsible for synchronizing the dictionary. Let’s define the Property and synchronize our collection.


  private Stimulsoft.Report.StiReport _ActiveReport;

  public Stimulsoft.Report.StiReport ActiveReport
  {
  get { return _ActiveReport; }
  set
  {
  _ActiveReport = value;
  this.NotifyOfPropertyChange(nameof(ActiveReport));
  }
  }

And the code to register the collection with StiReport.

  ActiveReport = new Stimulsoft.Report.StiReport();
  ActiveReport.RegBusinessObject("Products", _ProductCollection);
  ActiveReport.Dictionary.Synchronize();

This is where our problems begin. We do not have a property (the Report Property doesn’t allow Binding) exposed by Stimulsoft Designer to which could bind the StiReport Instance. We can do it pragmatically by assigning the Report Property, but that would involve breaking the MVVM Structure. We would prefer not to do that, atleast not directly. So what would be our workaround ?

Supervising Controller Pattern

The workaround lies with having a Supervising Controlling Pattern. The Supervising Controller allows the ViewModel to be aware of the View, but not depended on it. Now this can be a tricky situation if someone questions whether this would be breaking the MVVM, considering as per MVVM, the ViewModel should be completely independent of View. Pretty much true, but when all doors are closed, there is nothing wrong in making the ViewModel ‘aware‘ of View, as long as it is not dependent on View and we do minimalist code in View. Remember, there is a significant difference in being aware and being dependent.

So how do we implement the Supervising Controlling Pattern and make the ViewModel aware of the View. We first being by creating the Contract interface through which the ViewModel would be interacting with View. Let’s call it ISupervisorController

  public interface ISupervisingController
  {
  void UpdateReportControl(Stimulsoft.Report.StiReport Report);
  }

As you can see, it has a single method called UpdateReportControl, accepting the StiReport instance. Let’s go ahead and implement it in the View. We will make that only minimalist work is done in the code behind class.

  public void UpdateReportControl(StiReport Report)
  {
  ReportDesigner.Report = Report;
  }

So with that done, we come to the most important part – how do we get an instance of View in the ViewModel ? Thanks to Caliburn.Micro, we do have a solution for that as well.

Screen and IViewAware

The Screen class in Caliburn.Micro utilizes an interface ‘IViewAware, which exposes a method called OnViewAttached which gives us reference to the attached View. All that left to do is override the method and use our Supervising Controller interface to call the method from View, which sets the Report property of Designer Control

  protected override void OnViewAttached(object view, object context)
  {
  base.OnViewAttached(view, context);
  (view as ISupervisingController).UpdateReportControl(ActiveReport);
  }

That’s it, you have your .Net Object Collection synchronized with the Designer. The entire source code described in this post can be found here

Caliburn Micro #003 : Events (Short Hand Syntax)

Previously, We looked at one approach of binding Events to Controls. However, the convention based approach is one of the least used approaches in Caliburn Micro. Think about it, if you need to bind more than one event to the control, say for example, the Click Event and MouseOver Event, this approach would fall short.
Thankfully, Caliburn Micro provides another approach, based on Event Triggers, which solves this problem. While there is a long annotation version of the approach, we would stick to the shorthand version, which is, designed to be more developer friendly.
 
Convention Based Approach
 
Let’s declare a button and assign a OnClick Event to the control using the convention based approach first.
 <Button  x:Name="ClearTextMethod">Clear</Button>

Now, Let’s change the signature to Event Trigger based approach. First, we need to add a namespace in our XAML Headers.

xmlns:cal="http://www.caliburnproject.org"

Event Trigger Based Approach
And now we will attach the event. Notice the change in Syntax.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod]" />

As mentioned earlier, this approach allows us to attach more events to the Control. If we need to attach a MouseOver Event to the above button, all we need to do is add another pair of [Event][Action] separated by a semi-colon

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod];[Event MouseLeave]=[Action AnotherMethod]" />

Passing Parameter

We could also pass parameters to the method, with the same syntax.

A word of caution though when you pass a boolean parameter to the method. For example, invoking the method with following syntax doesn’t quite work.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod(true)]" />

The workaround is fairly simple thought, just include a single quote around the string representing True/False. We can modify the syntax as following.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod('true')]" />

Complete list of tutorials on Caliburn.Micro can be found here

Caliburn Micro #02 : BindableCollection & Events

In the previous part of this series, we looked into some of the basics of using Caliburn Micro. In this part, we will continue with few more examples, how to invoke a method on an event.

But before we do that, let’s expand our application a bit. Currently the application has two Text controls , wired up to a property (FirstName) in the View Model. Let’s expand it further and have 2 more properties, LastName and FullName.

Our expanded ViewModel Looks like following now.


private string _FirstName = "Jia Anu";

public string FirstName
 {
 get { return _FirstName; }
 set
 {
 _FirstName = value;
 NotifyOfPropertyChange(nameof(FirstName));
 NotifyOfPropertyChange(nameof(FullName));
 }
 }

private string _LastName;

public string LastName
 {
 get { return _LastName; }
 set {
 _LastName = value;
 NotifyOfPropertyChange(nameof(LastName));
 NotifyOfPropertyChange(nameof(FullName));
 }
 }

We will add additional controls to our View, and add the necessary binding.

        <!--Row 1 Starts here -->
        <Label Grid.Column="0" Grid.Row="0">Full Name</Label>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2"></TextBlock>
        <!--Row 1 Ends here -->

        <!--Row 2 Starts here -->
        <Label Grid.Column="0" Grid.Row="1">First Name</Label>
        <TextBox x:Name="FirstName" Grid.Row="1" Grid.Column="1"></TextBox>
        <!--Row 2 Ends here -->

        <!--Row 3 Starts here -->
        <Label Grid.Column="0" Grid.Row="2">Last Name</Label>
        <TextBox x:Name="LastName" Grid.Row="2" Grid.Column="1"></TextBox>
        <!--Row 3 Ends here -->

Bindable Collections

Let’s expand it futher, let’s introduce a model now. We will add a model in our Model Folder.

public class DeparmentModel
{
public string DepartmentName { get; set; }
public string Supervisor { get; set; }

}

And introduce two new properties for our View Model.

private BindableCollection _DepartmentCollection = new BindableCollection();

public BindableCollection DepartmentCollection
{
get { return _DepartmentCollection; }
set
{
_DepartmentCollection = value;

}
}

private DeparmentModel _SelectedDepartment;

public DeparmentModel SelectedDepartment
{
get { return _SelectedDepartment; }
set
{
_SelectedDepartment = value;
NotifyOfPropertyChange(nameof(SelectedDepartment));
}
}

We will delve more into BindableCollection later, but for now, let’s think of it as a means for binding to a combo box. Since we are not using any Db for this example, lets hard code some values in the constructor.

public ShellViewModel()
{
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Finance", Supervisor = "John Tommothy" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Development", Supervisor = "Alex Brown" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Human Resource", Supervisor = "Dennis Burton" });
}

We will add a Combo box and another Text Area in our XAML to accodomate the changes. The XAML looks like following now.

        <!--Row 4 Starts here -->
        <Label Grid.Column="0" Grid.Row="3">Department</Label>
        <ComboBox Grid.Column="1" Grid.Row="3" ItemsSource="{Binding DepartmentCollection}" DisplayMemberPath="DepartmentName"
                 SelectedItem="{Binding SelectedDepartment,Mode=OneWayToSource}" ></ComboBox>
                <!--Row 4 Ends here -->

        <!--Row 5 Starts here -->
        <Label Grid.Column="0" Grid.Row="4">Supervisor</Label>
        <TextBlock Grid.Column="1" Grid.Row="4" x:Name="SelectedDepartment_Supervisor"></TextBlock>
        <!--Row 5 Ends here -->

Run our application and you can now see the combo box in action. Everytime you change the Department, the corresponding Supervisor is displayed the TextArea.

Events and EventGuards

Now then, lets head to adding a button to clear the selected values. We will first introduce a method.

public void ClearTextMethod(string firstName,string lastName)
{
FirstName = string.Empty;
LastName = string.Empty;
}

We are passing two parameters, however we are not quite using it. However, the sigificance of the parameters come into light when we add our second method, CanClearTextMethod

public bool CanClearTextMethod(string firstName, string lastName)
{
return !string.IsNullOrEmpty(firstName);
}

Notice the naming patterns used for the methods and parameters. The ‘Can’ Method is named in such a way that it prepends ‘Can’ to the ClearTextMethod. This aids Caliburn Micro to recognize this method needs to be evaluated to enable CanClearTextMethod.

Also the parameters. They are named as similiar as the FirstName and LastName Properties. These are the properties which dictate whether to enable the method or not, which is being passed as paramers. Ensure the naming is correct and Caliburn Micro does the magic for you.

Lets add the necessary XAML for adding a button and wiring it up with the method.

        <Button Grid.Column="0" Grid.Row="5" x:Name="ClearTextMethod">Clear</Button>

The entire code sample for this examples can be found here. 

Complete List of Tutorials on Caliburn.Micro can be found here

Caliburn Micro #01 : Introduction

It has been long since i blogged, having caught up with the Product Release and Year End Vaccations. As the calender turns, it would be a good time to learn something new.

If you are building an WPF application and is looking out for MVVM Frameworks, you would be surprised with the amount of choices you are bestowed with. Despite Prism standing out as aruguably the most complete package available, there are times when you would like to try out a different framework. That brings us to Caliburn Micro, a light weight MVVM Framework, which might not be as powerful as Prism, but still does its work in a simple and easy way.

Bonus :  Caliburn.Micro Starter Kit Extensions for WPF is now available at Visual Studio Marketplace

Okay, that’s for an Intro, lets get our hands dirty and create a customary ‘Hello World’ app using Caliburn Micro. Let’s kick start our Visual Studio , create a new WPF Application and do the obvious step, add ‘Caliburn Micro’ Nuget package.

CM Demo 01.JPG

Once you have the necessary dependencies in, we will start with creating our ‘Hello World’ application. Normal WPF application would have ideally looked for the “StartupUri” Tag under your app.xaml to kick start your first page. The Caliburn.Micro works differently. So lets first go ahead and remove the StartUri tag and replace it with bit of XAML to ensure it takes advantages of features of Caliburn.Micro.

Our App.Xaml would now look like following.

<Application x:Class="App001.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:App001"
             >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <local:Bootstrapper x:Key="Bootstrapper"></local:Bootstrapper>
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

As you can see we have replaced the StartupUri and added a Resource Dictionary called Bootstrapper. At this point, Bootstrapper doesn’t exist, so we will go ahead and create it. Bootstrapper will act as the entry point for our WPF application and would point to the Screen that needs to be loaded first.


public class Bootstrapper : BootstrapperBase
 {
 #region Constructor
 public Bootstrapper()
 {
 Initialize();
 }
 #endregion

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

As seen in the code above, the Bootstrapper class is derieved from BootstrapperBase class from the Caliburn.Micro library. We have done two things here.
a) Called the Initialize method in the default constructor.
b) Override ‘OnStartUp’ method and called a single method, DisplayRootViewFor, pointing to the Base View Model which we want to load first. In this particular example, we have called it ShellViewModel.

As in the earlier case, we do not have the ShellViewModel class defined at the moment, which obviously becomes our next step. Prior to which, we will create 3 folders, each representing the three components of MVVM in the project – Models, Views, ViewModels. Remember naming the folders exactly the same, with names denoting plurals, so that we can take advantage of the Caliburn Magic.

We will now create the ShellViewModel Class under the ViewModels Folder.


public class ShellViewModel:Screen
{
}

Let’s keep it simple for the moment, san any properties and derieve it from Screen Class ( we will delve into other derivative options later). We will add the View for the ViewModel, again keeping it devoid of complicated controls for the sake of example.

        <TextBlock Text="Jia"></TextBlock>
        <TextBox>Jia</TextBox>

As seen the in code above, we have called it ShellView and have placed it under the Views Folder. The naming is of foremost importance here as the Caliburn Framework relies heavily on the naming conventions to wireup the View and View Model. Unlike, Prism you don’t need to set the ‘Autowireviewmodel’ property, this is being automatically done by the Caliburn framework as long as you follow the naming convensions.

For sake of simplicity being the first example, we have hard coded the values for TextBlock and TextBox, we will replace it with binding as we move on with the example.

That’s it, you are all set to run the basic ‘Hello World’.

Okay, let’s now add couple of Properties and bind them to our controls. Let’s go ahead and create the properties in ViewModel.


private string _FirstName = "Jia Anu";

public string FirstName
{
get { return _FirstName; }
set
{
_FirstName = value;
NotifyOfPropertyChange(nameof(FirstName));
}
}

Now let’s head towards the View and wireup the FirstName property. Modified XAML looks as below.

           <TextBlock Text="{Binding Path=FirstName, Mode=OneWay}" ></TextBlock>
        <TextBox x:Name="FirstName" ></TextBox>

Now you can run the application and see the magic of MVVM model in action via Caliburn Micro. In the next post, we will delve more into the CM features. The code for this project can be found here