WPF Prism concepts: regions

If you are a developer in the Microsoft environment and if you’re developing desktop apps, it’s likely that you’ve read something about Prism.  If you don’t then this is what Prism is about:

Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms. (from the Prism’s Official GitHub description)

The Prism documentation is very detailed but with this blog post we are more practical and examples-driven. If you want to dive into the details of Prism the official documentation is the best place.

Definition

A region is a placeholder in the shell of a Prism application for content that will be loaded at runtime. Regions are defined as UI elements like ContentControl, ItemsControl, TabControl or a custom control.

The content of a region is a view. We can access regions in a decoupled way by their name and they support dynamically adding or removing views.

Example with view discovery

So now it’s coding time!

The first thing we need is to setup our app to be a Prism-app. At this point we have a clean Prism-App.

Then, we create a region in our MainWindow. This is the XAML code.

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <Grid>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
    </Grid>
</Window>

We can see that the regions are defined as XAML attached properties. In the code above our region is called RegionA.

Now we have our region defined but no content to load into. We create a new user control in the Views subfolder and name it ViewA.xaml.

Immagine

In this class in the XAML part we write:

<UserControl x:Class="XXXXX.Views.ViewA"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              >
    <Grid>
        <TextBlock Text="View A" FontSize="38" />
    </Grid>
</UserControl>

That’s good! We have our region and a view. Now it’s time to tell Prism that RegionA is the target where to load the ViewA view. In the code-behind of the MainWindows.xaml we write:

using Prism.Regions;
using System;
using System.Windows;

namespace XXXXX.Views
{

    public partial class MainWindow : Window
    {
        public MainWindow(IRegionManager regionManager)
        {
            InitializeComponent();

            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }
            regionManager.RegisterViewWithRegion("RegionA", typeof(ViewA));
        }
    }
}

With the above code for the constructor we are registering that RegionA has to be populated with an instance of ViewA view. The region manager is passed as a parameter by the DI container (in our case Unity). This technique is called View Discovery. The result is:

Screenshot_1

Example with View Injection

Now we explore the View Injection technique that enables us to load and unload the content of a region dynamically at runtime.

We create a new view, ViewB, like we did for ViewA under the Views folder.

<UserControl x:Class="XXXXX.Views.ViewB"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"            >
    <Grid>
        <TextBlock Text="View B" FontSize="38" Foreground="#FF0023FF" />
    </Grid>
</UserControl>

We edit the MainWindow to add another region and a button to fire our code:

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <StackPanel>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
  <Button Click="Button_Click" >Load region B</Button>
<Button Click="Button_Clear_Click" >Clear region B</Button>
<ContentControl prism:RegionManager.RegionName="RegionB" />
    </StackPanel>
</Window>

And the code behind

public partial class MainWindow : Window
    {

        private readonly IRegionManager _regionManager;
        private readonly IUnityContainer _container;

        public MainWindow(IRegionManager regionManager, IUnityContainer container)
        {
            InitializeComponent();
            //view discovery
            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }

            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            _regionManager = regionManager;
            _container = container;

            _regionManager.RegisterViewWithRegion(RegionNames.RegionA, typeof(ViewA));

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //We get from the container an instance of ViewB.
            var view = _container.Resolve<ViewB>();

            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //We inject the view into the region.
            region.Add(view);
        }

  private void Button_Clear_Click(object sender, RoutedEventArgs e)
        {
            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //Clears the content.
            region.RemoveAll();
        }

    }

What we’re doing here is to get our target region by using the RegionManager class.

The RegionManager class is responsible for creating and maintaining a collection of regions for the host controls. The RegionManager uses a control-specific adapter that associates a new region with the host control. The following illustration shows the relationship between the region, control, and adapter set up by the RegionManager. (Prism official docs)

When we have a reference of the region (RegionB in this case) we can add or remove content with the Add or the Remove/RemoveAll methods.

Screenshot_2

TL;DR

In this blog post we explored the concept of Region. Regions are useful conteiners to create our UI in a structured and dynamic way. We loaded content with the discovery and the injection technique.

In the next blog post we’ll study other Prism’s concepts.

Happy coding!

Reference

Prism official documentation (http://prismlibrary.readthedocs.io/en/latest/)
Prism Github page (https://github.com/PrismLibrary)

Advertisements

SOLID principles by example: Dependency inversion

This is the last blog post about the SOLID principles in object-oriented programming and we talk about the Dependency Inversion Principle (DIP).

Screenshot_1

The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

Read More »

SOLID principles by examples: Liskov Substitution Principle

In this post we’re going to explore the third of the SOLID principles: the Liskov Substitution Principle (LSP).

The most practical definition of this principle was written by Robert C. Martin in his book Agile Software Development, Principles, Patterns, and Practices.

Subtypes must be substitutable for their base types.

The concept was introduced by Barbara Liskov in 1987. The formal definition is:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

For our daily activities we must remember that a subclass should override the parent class’ methods in a way that doesn’t break functionality from a consumers’s point of view.

Example


abstract class MusicalInstrument
    {
        public abstract void PlayANote();
    }

class Piano : MusicalInstrument
    {
        public override void PlayANote()
        {
            PressKey();
        }

        private void PressKey()
        {
            //Press a piano key.
        }
    }

class Saxophone : MusicalInstrument
    {
        public override void PlayANote()
        {
            Blow();
        }

        private void Blow()
        {
            //Blow air into the instrument.
        }
    }

The evergreen example

To better underestand LSP let’s examine this classic example. It’s a classic because it’s easy to understand and very meaningful. We start with this question:

Is a square a special rectangle in OOP?

We try to answer this question with this simple class hierarchy: a Rectangle as base class and a Square class that inherits from it. In the Square class we override the behavior of the setters to enforce that the the Heigth and Width properties have the same value.

class Rectangle
    {
        public virtual float Heigth { get; set; }
        public virtual float Width { get; set; }
        public virtual float Area
        {
            get { return Heigth * Width; }
        }
    }

class Square : Rectangle
    {
        private float _heigth;

        private float _width;

        public override float Heigth
        {
            get
            {
                return _heigth;
            }
            set
            {
                _heigth = value;
                _width = value;
            }
        }

        public override float Width
        {
            get
            {
                return _width;
            }
            set
            {
                _width = value;
                _heigth = value;
            }
        }
    }

Now we have to remember that a subclass must override the base class in a way that it doesn’t break functionality from a client’s POV. We write these two tests to check.


[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestWithRectangle()
        {
            Rectangle sut = new Rectangle();
            sut.Heigth = 3;
            sut.Width = 7;

            Assert.AreEqual(21, sut.Area);
        }

        [TestMethod]
        public void TestWithSquare()
        {
            Rectangle sut = new Square();
            sut.Heigth = 3;
            sut.Width = 7;

            Assert.AreEqual(21, sut.Area); //This test will fail. Area equals 49.
        }

    }

So it’s clear that in OOP a square isn’t a particulare case of a rectangle. How can we do to better organize these classes? The typical approach consists of creating an abstract class (or an interface). For example

abstract class Shape
    {
        public abstract float Area { get; }
    }

 class Rectangle : Shape
    {
        public float Heigth { get; set; }
        public float Width { get; set; }
        public override float Area
        {
            get { return Heigth * Width; }
        }
    }

    class Square : Shape
    {
        public float Edge { get; set; }

        public override float Area
        {
            get { return Edge * Edge; }
        }
    }

Now our code states that both the Rectangle class and the Sqare class are Shapes which is true. Our code is also safer and we don’t have any situation where a client will receive unexpected values.

TL;DR

In this post we explored the Liskov Substituion Principle (LSP) and we learned that it’s not true that real-life objects always maps to the same OOP structure / class ecosystem. When also tried to improve the wrong example with the simple technique of adding an abstraction layer (the Shape class).

1 anno di blogging

Oggi questo blog compie 1 anno.

Nonostante tante cose è sempre rimasto attivo e ne sono orgoglioso. Ok, non è così attivo come vorrei (ha vissuto un paio di mesi di pause) ma ha attraversato eventi decisamente importanti come:

  1. La nascita del mio secondo figlio;
  2. Picchi lavorativi dovuti a nuovi clienti;
  3. Un trasloco verso una casa nuova;
  4. Notti insonni dovute al punto 1.

È nato per sfida personale sull’argomento costanza: spesso mi dico che non sono bravo a portare avanti le cose per lunghi periodi di tempo e volevo migliorare. È nato anche perché sono stato influenzato da Jeff Atwood, Scott Hanselman, Frank Bettger e da tantissimi blog-post che indicano come scrivere articoli, anche semplici, ci rende più ferrati sull’argomento.

Ho iniziato così a sperimentare per trovare la mia voce, il mio modo di raccontare le cose e di trasmetterle.

Un grosso cambiamento è avvenuto a maggio quando sono stato alla Microsoft House per un evento sul Dekstop Bridge. Parlando con Matteo Pagani e altri ragazzi ho scoperto quanto un blog sia un esercizio svolto da molti. È stata un’iniezione di motivazione e allo stesso una scoperta perché ha cambiato il contenuto dei miei articoli. Ho scoperto quanto mi piaccia scrivere dei miei esperimenti che svolgo per curiosità su tecnologie informatiche che non utilizzo nella mia quotidianità al lavoro: mi aiuta a fissare i concetti e ciò che scopro può essere utile a qualcun altro.
Alcuni esperimenti con UWP si sono trasformati in un possibile business per un conoscente che mi ha chiesto informazioni. Le prove con Prism sono state impiegate per un prodotto nuovo in azienda portato avanti da dei colleghi. Gli articoli su DZone condivisi da questo blog raggiungono migliaia di visite e questo blog ha raggiunto 200 visitatori unici al mese in luglio. Certo altri blogger fanno queste cifre al giorno ma per me è già tanto.

Il mio caloroso consiglio è quello di cominciare un blog anche voi se siete indecisi: condividete il vostro interesse per qualcosa per il puro piacere di insegnare, per divertirvi e per imparare. A me ha portato solo cose buone. Trovate un ritmo che siete in grado di mantenere e mantenetelo a tutti i costi. Non traete conclusioni prima di un anno di blogging più o meno continuo.

Queste sono le mie conclusioni: ne vale la pena e continuerò più che posso.

SOLID principles by examples: open/closed

This post continues the analisys of the SOLID principles started some blog posts ago. This is the turn for the Open Closed Priciple (OCP).

The definition

An object/entity should be open for extension but closed for modification.

What we are basically talking about is to design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.

Read More »

SOLID principles by examples: single responsability

This blog post will explain with simple examples the Singe Responsabily Principle of SOLID agiles principles to better understand how we can improve our daily coding activites. In future post I’ll cover the other four priciples.

The Definition

A class should have only one reason to change.

Defined by Robert C. Martin in his book Agile Software Development, Principles, Patterns, and Practices it is the first of the five SOLID agile principles. What it states is very simple, however achieving that simplicity is not so obvious.

Read More »