Widget to Widget Communication in UWP Dashboard app

<p><a href="http://mikaelkoskinen.net/posts/files/573eaaea-470a-495c-9959-c606e83e726c.gif"><img title="9f487017-1cc8-4ab2-88ec-eca71fab35c2[4]" style="float: right; display: inline" alt="9f487017-1cc8-4ab2-88ec-eca71fab35c2[4]" src="http://mikaelkoskinen.net/posts/files/bfc0925d-2683-4a56-aaa4-a9d1fb12291d.gif" width="386" align="right" height="343"></a></p> <p>In our <a href="http://mikaelkoskinen.net/post/uwp-dashboard-widget-app-caliburn-micro" target="_blank">last tutorial</a> we created an UWP widget dashboard app (and platform) using Caliburn.Micro. The platform in its first version is very basic and we ended up listing many improvements to it:</p> <ul> <li>Instead of always having all the widgets, user should be able to add and remove widgets.</li> <li>Common widget elements, like title and action buttons.</li> <li>Different sized widgets instead of a single fixed size.</li> <li>Ability to send notifications from a widget to a widget using Event aggregator.</li> <li>Ability to send notifications from a widget to the shell using Event aggregator.</li></ul> <p>In this tutorial we’re going to show how it’s possible to do widget to widget communication.</p> <h2>Background</h2> <p>We want our widgets to be self contained and isolated, meaning we don’t want them to interfere with the other widgets and we don’t want our shell to have to care about which widgets it is hosting.</p> <p>Widgets can communicate with each directly and indirectly. Direct way (calling a method from another widget) introduces coupling and makes it harder to keep widgets isolated. Preferred way is to use indirect messaging. </p> <h2>Direct communication</h2> <p>It’s possible to communicate directly from a widget to an another but <strong>this isn’t recommended. </strong>If you really need to do this, a widget can reference other widgets through its Parent-property (which is provided by Caliburn.Micro). The following code shows how you can directly call methods from other hosted widgets:</p><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> var widgets = ((ShellViewModel) this.Parent).Items;
foreach (var widget in widgets)
{
if (widget is CustomerListViewModel customerList)
{
customerList.AddNewCustomer(FirstName, LastName);
}
}</pre>
<p>But as mentioned, you shouldn’t do this in most cases.</p>
<h2>Indirect communication using the Event Aggregator</h2>
<p>Caliburn.Micro contains an <a href="http://mikaelkoskinen.net/post/uwp-multi-view-communication" target="_blank">event aggregator</a>. Event aggregator is a “middle man” which you can use to handle widget-to-widget, widget-to-shell and shell-to-widget communication. </p>
<p>With event aggregator your widgets (and shell) can raise messages. Any other widget can subscribe to the messages they are interested in. For example “NewCustomerWidget” can raise “NewCustomerAdded” message. “CustomerListWidget” can listen (to subscribe) to this message and react to it, by for example refreshing its view.</p>
<p>Given that we have NewCustomerWidget, it can can raise desired message using IEventAggregator.Publish(). First we need to define the message:</p><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> public class NewCustomerCreated
{
public string FirstName { get; }
public string LastName { get; }

public NewCustomerCreated(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}</pre>
<p>Then we can raise (publish) the message from our widget:</p><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> public class NewCustomerViewModel : Screen, IWidget
{
private string _lastName;
private string _firstName;
private readonly IEventAggregator _eventAggregator;

public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyOfPropertyChange(() =&gt; FirstName);
NotifyOfPropertyChange(() =&gt; CanSave);
}
}

public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyOfPropertyChange(() =&gt; LastName);
NotifyOfPropertyChange(() =&gt; CanSave);
}
}

public bool CanSave
{
get
{
if (string.IsNullOrWhiteSpace(FirstName))
return false;
if (string.IsNullOrWhiteSpace(LastName))
return false;

return true;
}
}

public NewCustomerViewModel(IEventAggregator eventAggregator)
{
this._eventAggregator = eventAggregator;
}

public void Save()
{
this._eventAggregator.PublishOnUIThread(new NewCustomerCreated(FirstName, LastName));
}
}</pre>
<p>Main things to notice: </p>
<ul>
<li>IEventAggregator is passed through constructor.</li>
<li>Message is raised using PublishOnUiThread.</li></ul>
<p>Now that our widget can publish messages, we can add subscribers who can react to these messages. Here’s how we can make our “CustomerListWidget” to update its view anytime new customer is added:</p><pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> public class CustomerListViewModel : Conductor&lt;Customer&gt;.Collection.AllActive, IWidget, IHandle&lt;NewCustomerCreated&gt;
{
public CustomerListViewModel(IEventAggregator eventAggregator)
{
eventAggregator.Subscribe(this);

this.Items.Add(new Customer("Test", "Customer"));
this.Items.Add(new Customer("Another", "One"));
this.Items.Add(new Customer("Mikael", "Koskinen"));
}

public void Handle(NewCustomerCreated message)
{
this.Items.Add(new Customer(message.FirstName, message.LastName));
}
}</pre>
<p>Main things to notice:</p>
<ul>
<li>IEventAggregator is passed through constructor and we subscribe our view model to it.</li>
<li>Our view model implements IHandle&lt;NewCustomerCreated&gt;</li></ul>
<p>When we now run the app, we can see our two customer related widgets:</p>
<p><a href="http://mikaelkoskinen.net/posts/files/7446262b-3dad-47c7-b76d-227dad3d7ae8.png"><img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="http://mikaelkoskinen.net/posts/files/c79506e2-3317-494f-be10-e7a77c7ba624.png" width="377" height="338"></a></p>
<p>If we now create a new customer, we can see that the customer list is updated:</p>
<p><a href="http://mikaelkoskinen.net/posts/files/6c64a8a1-5fcc-429b-aba6-329d2e6ac382.gif"><img title="9f487017-1cc8-4ab2-88ec-eca71fab35c2" style="display: inline" alt="9f487017-1cc8-4ab2-88ec-eca71fab35c2" src="http://mikaelkoskinen.net/posts/files/c4956fc4-5c0b-4927-9907-c42b33a4029a.gif" width="372" height="330"></a></p>

<h2>Conclusion</h2>
<p>You can use direct widget-to-widget communication but instead you should prefer indirect messaging. Event aggregator makes it possible for widgets to publish and subscribe to messages.</p>
<p><a href="https://github.com/mikoskinen/blog/tree/master/UWP-WidgetCommunication" target="_blank">The source code for this tutorial</a> is available through GitHub.</p>