Dude, where’s my Kaizen?

From .NET to Ruby to whatever interests me next

Diving into the StoryTeller trunk, Part 11.2: More on Commands

Let’s take a look at some of the questions I left unanswered in the last post.

Is the basic GoF Command pattern sufficient for a modern composite application?

The basic GoF Command pattern has no notion of visual state of a Command, such as (Is)Enabled or (Is)Visible. Its original purpose was to encapsulate an action, so that it can be passed around and executed at some later point of time. Not more, not less.

The basic Command interface
1
2
3
4
public interface ICommand
{
  void Execute();
}

Obviously real world desktop apps need something a bit more sophisticated. I’ve seen several infrastructures in my (not so old) career so far (home grown as well as OS alternatives), which extended this basic idea with at least one of those properties mentioned above. Take for instance the P&P Composite UI Application Block (now better known as part of the Smart Client Software Factory). CAB implements a delegate based variation on the Command pattern. The delegate represents the action which is passed around. However, this delegate is managed by the Command class which has a notion of Status.

CommandStatus in CAB
1
2
3
4
5
6
public enum CommandStatus
{
  Enabled, //visible and enabled
  Disabled, //visible and disabled 
  Unavailable //invisible 
}

The WPF Command infrastructure version of the Command interface is more like the original pattern and adds the Enabled Property and an EnabledChangedEvent to the interface definition.

WPFs ICommand interface
1
2
3
4
5
6
public interface ICommand
{
  void Execute();
  bool Enabled { get; }
  event EventHandler EnabledChanged;
}

To be honest, the Command interface never looked like the original GoF definition in ANY APPLICATION or project I’ve worked on so far. It always had a slight modification in one or another way.

StoryTeller’s Command interface

StoryTeller is a WPF based application, so naturally it gets the WPF Command infrastructure out of the box. However it composes the WPF ICommand into a StoryTeller specific structure, the IScreenAction.

The ScreenAction abstraction
1
2
3
4
5
6
7
8
9
10
public interface IScreenAction
{
  bool IsPermanent { get; set; }
  InputBinding Binding { get; set; }
  string Name { get; set; }
  Icon Icon { get; set; }
  ICommand Command { get; }
  bool ShortcutOnly { get; set; }
  void BuildButton(ICommandBar bar);
}

IScreenAction extends the capabilities of the original GoF-Pattern with a lot of metadata, mostly for visual aspects (Icon, Description). If you’re wondering why he included visual aspects: That basically tries to solve a reoccurring problem in composite apps: In composite applications modules are not known at compile time to the infrastructure. Neither are all their capabilities and how they might be displayed in the infrastructure shell. Because of that, the infrastructure needs a dynamic, deferred way for doing the shells visual configuration at application startup. One way to implement this is to delegate the responsibility for setting this up to the modules itself. This can be done during the module load time or every time a screen is displayed. This fits very well with the idea of the Open Closed Principle, since adding new modules/screens doesn’t require any reconfiguration/recompilation of other modules or the infrastructure. This is more or less the approach that StoryTeller takes.

Some personal thoughts on IScreenAction

I’ve worked on three applications in the past which followed down the same road. One thing I noticed throughout those three applications is that this approach isn’t really well suited when you’ve got strict and/or complex requirements about how the UI of an application should look. Let me clarify a bit what I mean:

  • The Ordering Problem. Even if you organize tools representing commands in a simple toolbar (as StoryTeller does) you can very easily get into situations where the product owner wants to have the tools in a very specific order which is different to module load order, some internal event order, whatever. I’ve encountered this several times now. First time we solved this by introducing a global constant class containing tool names. Very, very bad idea, do not repeat this. This introduces a kind of hidden temporal coupling, because now modules must be loaded in a particular order (so that a tool already exists to which we can refer by name). StoryTellers take on this is a bit better (but IMHO not much). The Icon class has an Integer based Order property. All tools get sorted based on this property in StoryTellers CommandBar when it’s reloaded. This is less coupled, because it eliminates the temporal aspect of the coupling, but still has coupling.
  • API bloat with visual aspects. One area where I really started to find this approach annoying is when you stop having simple toolbars and start to use more complex menu types like for instance the Ribbon. Taking the ribbon as an example: Now don’t have simply an ordering problem, but at minimum an icon problem (Normal icon vs. Quick Access Toolbar), a size problem (Displayed large or small) and a positioning problem (/Tab/Group/ElementGroup vs. /ApplicationMenu/Left). We added all those stuff to our Command registration and guess what, we weren’t happy with that. We created a monster API actually doing very little.

So what do I (currently) prefer? Our current project (also using the Ribbon) completely strips the visual aspect of the Command. Our Command API looks very much like the WPF one, with the only addition of an Id property. The whole visual aspect is configured using an XML file which is loaded at application startup.

Using xml to wire up the ribbon
1
2
3
4
5
6
7
<Ribbon>
   <Tab>
      <Group>
         <Button imageId=CancelIcon commandId=CommandXYZ />
      </Group>
   </Tab>
</Ribbon>

I think you get the point. It works very well for our scope. (Slight warning though: This solution might not be the best in case you need to represent menu state based on dynamically loaded data).

See you next time for: Commands strike back ;-)


StructureMap: Registry usage

I recently read something like this on Twitter:

It feels wrong to have registration and scanning in the Registry class

I absolutely second that. One of the decisions in my current project (a composite smart client) was to separate these two things, in order to give clear guidance on “which to use when”. Here is our setup:

Bootstrapping our container
1
2
3
4
5
6
7
8
9
10
ObjectFactory.Initialize(x =>
{
  x.AddRegistry(new InfrastructureRegistry());
  x.Scan(scanner =>
  {
          scanner.AssembliesFromPath("Modules");
          scanner.Convention<ProjectConventions>();
          scanner.LookForRegistries();
  });
});
  • We packaged our conventions for the project into a single composite convention. This includes the easier mappings ala IFooFoo, as well as more complex conventions for services which are automatically instrumented on creation via Castle.DynamicProxy.
  • Registry classes are used for all the stuff we’re not able to configure via conventions.
    This includes mappings from interfaces to types with completely different names, adding externally created stuff to the container or configuring complex constructions like a composite.
  • There is exactly 1 Registry per module in our application (+ 1 for the infrastructure).
  • Registry classes are dynamically found during the scan process by looking into each assembly configured in the Scanner.

Any opinions? If you’re using Registries, how do you use them?


Changes in StructureMap 2.5.4

Interesting what some people do during the Christmas holidays. In the case of Jeremy D. Miller this was releasing a new version of StructureMap and working heavily on the Fubu MVC codebase. Today I had the pleasure to migrate my current projects codebase (which previously used Unity and Unity.Interception) to the newest StructureMap version 2.5.4 and Castle.DynamicProxy2.

It was an interesting experience mostly because I tried to re-use some code pieces for setting up conventions from an earlier project based on StructureMap 2.5.3. Quite a few things have been changed in the API. Needless to say, all for good. I just wanted to give a quick overview of the things I noticed.

ITypeScanner was replaced by IRegistrationConvention

If you wanted to write custom conventions in StructureMap 2.5.3 you needed to implement the ITypeScanner interface (An example is described here).

ITypeScanner was replaced by IRegistrationConvention
1
2
3
4
5
6
7
8
9
10
11
//StructureMap 2.5.3 
public interface ITypeScanner
{
  void Process(Type type, PluginGraph graph);
}
  
//StructureMap 2.5.4 
public interface IRegistrationConvention
{
  void Process(Type type, Registry registry);
}

As you can see, it’s not only a renaming. The signature of the Process-method has changed, too. It now uses the good old Registry class for doing the registration. Very consistent, good choice. Modifying the PluginGraph always left me with the feeling that I was digging too deep into the StuctureMap internals.

TypeRules base class has been replaced with Extension methods

In the past you could re-use some utility methods for reflection (like checking whether a type is concrete, etc.) by inheriting from the TypeRules class. This class has been completely removed, but the functionality is still available via Extension methods.

Lot’s and lot’s of renaming

A lot of renaming has been done. The most interesting stuff happened in the Registry class.

Renamings in the fluent api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//StructureMap 2.5.3
public class MyRegistry
{
    public MyRegistry()
    {
        ForRequestedType<IFoo>().TheDefaultIsConcreteType<Foo>();
        ForRequestedType<IBar>().TheDefaultIsConcreteType<Bar>().AsSingleton();

        ForRequestedType<IFoo>().TheDefault.IsThis(new Foo)
        ForRequestedType<IBar>().TheDefault.Is.ConstructedBy(x => new Bar());
    }
}

//StructureMap 2.5.4
public class MyRegistry
{
    public MyRegistry()
    {
        For<IFoo>().Use<Foo>();
        ForSingleton<IBar>().Use<Bar>();

        For<IFoo>().Use(new Foo)
        For<IBar>().Use(x => new Bar());
    }
}

The new version is a lot less wordier and a lot more consistent in naming. It also feels very familiar, although I’m unable to determine why.

Some new slick features I noticed

From playing around with the StructureMap trunk version during the “Diving into the StoryTeller Series” I already stumbled over this killer feature.

Convention based registration
1
2
3
4
5
_container = new Container(x => x.Scan(s =>
{
   s.AssemblyContainingType<ISomeService>();
   s.ConnectImplementationsToTypesClosing(typeof(IHandler<>));
}));

Jimmy Bogard has already written an excellent article about that particular feature. So instead let us take a look at this new ability.

Accessing the container model
1
ObjectFactory.Model.GetAllPossible<IInitializable>();

This resolves all instances from the configuration model which implement the IInitializable interface.

Stuff you don’t see

If you’ve followed Jeremy D. Miller closely on Twitter you may have heard that the biggest change in the new release has happened under the hood of StructureMap. In previous versions StructureMap used Reflection.Emit to emit an assembly for the construction of the types at runtime. This has been completely rewritten using ExpressionTrees. I’m quite curious how he implemented that.

Feels like yet another source to learn has emerged ;-)


Diving into the StoryTeller trunk, Part 11.1: Commands

Welcome back to the Diving into the StoryTeller trunk series. The main topic for the last couple of posts about StoryTeller is its Command handling or to be a bit more specific the reoccurring problem of how Screen related Commands are managed in the app infrastructure. Couple of posts? Yeah, right. Today’s post is going to be a bit shorter than the usual posts in the series. When I started to write this post I quickly realized that this topic contains more aspects to talk about than I had originally anticipated. Besides that Christmas is near, I’m running out of time for this year and just wanted to get at least some bits of the content out there before going on vacation. Today’s post is going to be more general one on the topic.

The Command Pattern

A lot of the content in this series dealt exclusively with how the StoryTeller UI layer manages Screens in its content area, but as you know most of the time an application consists of more parts than just the plain content area. A typical desktop application is probably going to have some sort of Mainmenu, a Statusbar and of course Contextmenus. Items displayed in those areas very often represent actions an application can perform. They act as a trigger of those actions. A typical way to implement this is using the GoF-Command Pattern, which separates the invoker of an action (for instance a button) from the receiver instance which executes the action by introducing the Command abstraction. A Command encapsulates the knowledge needed for an invokation of the receiver instance, so that it can be executed at a later time.

Commands are potentially contextual

An application can have lots and lots of Commands. While some of these Commands are available all of the time, some of them can only be executed in a particular context. A typical example for Commands of the first category might be the “Exit application” Command. A typical example for the latter category might be the “Undo” Command or “Redo” Command in all kinds of text editors, which can only be executed when the currently viewed document has some changes. It’s not uncommon to have lots of contextual Commands in an application that are only related to a very specific Screen or Screen state. When we think in terms of usability, the least a user should be able to take granted from an app is that the app appropriately shows which actions can be performed at a particular point of time. This can be achieved by enabling / disabling related items depending on the availability of the Command (be it manually or through databinding). Sometimes though,it might be a better approach to have an even more contextualized UI that only shows the commands related to the current context. So for instance if no code editor view is shown in Visual Studio than the “Undo” and “Redo” Commands should also not be visible (NOTE: VS doesn’t actually behave that way). I think this idea of contextualized UIs becomes more and more popular. Office 2007/2010 was build with this idea in mind.

Commands in a Composite UI

Composite UIs which follow the Open / Closed Principle add another problem to the mix. When new modules or new screens are loaded into a composite app, they shouldn’t need to modify the app infrastructure in order to add their related commands. The app infrastructure needs to provide a way to plug those commands in without modification. This also includes their visual representation (Text, Tooltip, Icon, etc.).

Questions we should take a closer look at

  • Do we need to differentiate between types of Commands?
  • Who is responsible for adding / registering commands?
  • How is the visual representation of commands configured?
  • Who is responsible for deciding whether Commands are available?
  • Is there build-in .NET Framework support for this?
  • Of course: How does StoryTeller implement all this?

I’m afraid that’s all for today. I wish you all merry Christmas and a happy new year. See you in 2010



What’s next?

With the “Diving into the StoryTeller trunk series” coming to an end in the near future, I’m currently looking into several ideas for future posts. Here’s what I’m currently thinking about:

  1. xUnit.BDDExtensions feature walkthrough and documentation Let’s be honest it’s currently not documented at all. I failed big time at documenting its usage scenarios and behavior so far. However, since more and more projects at my current client are starting to use it I’m definitely going to fix this …

  2. Look into various options to implement the Active Object Pattern I’ve been reading several papers about infrastructures for command execution lately. It’s an interesting topic for distributed scenarios (for instance used in a CQSR design), but also for local scenarios when you start to think about multi core / concurrent programming. As modern applications are becoming more and more connected on the one hand and need to use local resources more efficiently on the other (because processors won’t get a lot faster in the near future) I think there’s a huge need for having a simple consistent design for both. Things I’d like to look into are the Concurrency Coordination Runtime, the .NET 4.0 Task Parallel Library and Application Spaces, as well as more specific topics like integrating such an infrastructure with an MVVM design.

  3. Dive into the Caliburn trunk Last but not least I would love to spend some time with Caliburn since WPF is more and more on my radar and Caliburn seems to fully embrace and extend a lot of the original WPF design ideas in a composite context. I think I would do something similar to the StoryTeller series.

So, what do you think? Any preferences? Any priorities?


Diving into the StoryTeller trunk, Part 10: Coordination Baby!

So far in this series I’ve talked extensively about what I consider the most of the important parts in the StoryTeller UI design. This includes Screens, the ScreenCollection, ScreenSubject, ScreenFactory, EventAggregation and the application of Convention of Configuration in general. You could say that we mostly talked about ingredients. Today I would like to take some additional time in order to show how this is all assembled into an actual API. Those of you who’ve already spend some time with the StoryTeller codebase too or have watched one of the many screencasts about the Screen Activation Lifecycle probably know what I’m going to show today. Today is all about the ScreenConductor.

ScreenConductor vs. Application Controller

Before we dive into the actual code, let’s take a short break and talk a little bit about a more high level view on the ScreenConductor and the role the conductor is fulfilling in an application. Martin Fowler identified the pattern ApplicationController some years ago as

A centralized point for handling screen navigation and the flow of an
application.

It’s kind of a coordination structure which manages / coordinates the lifecylcle of child screens in an application as well as the lifecycle of the application shell itself (think about controlled shutdown for instance). You can think of the ApplicationController as a Facade client code can call in order to create/activate/deactivate screens in an application. This Facade defines a nice separation between application code on the one side and the UI infrastructure on the other side. It shields away implementation details of how the application is actually displaying screens (tab style, web style, etc) from the client and also provides a nice point for handling scenarios like dirty checks on screens. As an application grows over time, it’s a good idea to break down the ApplicationController into several collaborating classes and decouple its implementation details from another in order to make the system more manageable and maintainable. Adding a new screen to the application for instance should not require a change in one of the UI infrastructure classes. When breaking down the ApplicationController into several collaborating classes a good lead is to use the Single Responsibility Principle in order to identify responsibilities which can be extracted.

That’s exactly what Jeremy D. Miller did in his Screen Activation Lifecycle. He broke down the ApplicationController pattern into several smaller responsibilities, the most important beeing

  • the ScreenCollection (which keeps track of all existing screens and the one beeing the active screen)
  • the ScreenSubject (which is used to separate identification and creation of a screen from the screen itself)
  • Screens (which provide the content beeing displayed and hooks for instance for the dirty check when the application closes)
  • and the ScreenConductor.

Jeremy describes the ScreenConductor and its responsibilities as the following:

“Controls the activation and deactivation lifecycle of the screens within the application. Depending on the application, the conductor may be synchronizing the menu state of the shell, attaching views in the main panel or otherwise, and calling hook methods on the Presenter’s to bootstrap the screen. It may also be just as important to deactivate a screen when it’s made the inactive tab to stop timers. My first exposure to a ScreenConductor was an insurance application that was built with web style navigation. Anytime the user moved away from a screen we needed to check for “dirty” screens to give the user a chance to deal with unsaved work. On the other hand, we also had to check the entry into a requested screen to see if we could really open the screen based on pessimistic locking or permission rules. We pulled our a Layer SuperType for our Presenters for methods like CanLeave() and CanEnter(). The ScreenConductor would use these methods and others to manage screen navigation.”

To me the ScreenConductor is more or less an OCP-fied subset of the original ApplicationController pattern, focussing on the coordination and facade ideas of the original pattern.

A short episode in the Screen Activation Lifecycle

Let’s give our discussion a bit more detail. So far it was rather abstract. Before looking into the actual code I would like to walk you through a typical usecase which depicts how those components actually work together. The example Jeremy mostly uses for this is “Opening a source code file in Visual Studio” . I’m lazy, so I’m going to reuse this one.

“Consider you double-click a file in the Solution Explorer of VS. When you do this for the first time a new tab displaying the contents of the file will be opened. Doing the same thing a second time will not open a new tab, but rather focus the existing tab displaying the contents of the file.”

It’s actually easy to translate this story into a more abstract version using the responsibilities described in this post so far.

“Consider you want to open a Screen via a ScreenSubject. When the ScreenSubject detects that no related Screen is being displayed to the user, a new Screen will be created by the subject and then added to the ScreenCollection. Doing the same thing a second time will not open up a Screen, but rather activate the existing SCREEN, because the ScreenSubject detected that the Screen is already open.”

The interesting sidenode in this design is that from a client code perspective there is no difference between opening up a screen and activating a screen. Really nice …

Usecase: Opening a Screen

Now that you’re familiar with the first scenario, time to show some code. I’ve shown parts of this before in the previous post (Sorry for the duplication), but added some bits in order to illustrate this example. From the outside world a call to the ScreenConductor for this usecase might look like this.

Opening a Screen
1
2
var subject = new CSharpFileSubject(@"C:\\end\\of\\the\\world.cs");
screenConductor.OpenScreen(subject);

Notice that all data needed for creating the actual Screen will be passed in with the concrete ScreenSubject implementation.

A ScreenSubject
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class CSharpFileSubject : IScreenSubject
{
  private _fileName;

  public CSharpFileSubject(string fileName)
  {
    _fileName = fileName;
  }

  public bool Matches(IScreen screen)
  {
    return screen is SourceCodeScreen &&
      string.Equals((SourceCodeScreen)screen.FileName, _fileName));
  }

  public IScreen CreateScreen(IScreenFactory screenFactory)
  {
    var screen = screenFactory.Build<SourceCodeScreen>();
    screen.File = _fileName;
    return screen;
  }
}

This is not quite the code I would write for a real system, but I think you get the point. Two methods need to be implemented for the IScreenSubject interface. This is bool Matches(IScreen) which identifies a related screen and IScreen CreateScreen(IScreenFactory) which is used to create the screens. I really like this kind of API design since it gives you all sorts of extension points without the need to open up the actual infrastructure. Want to show a WaitCursor while you create the Screen? Go ahead. Want to do some loading before the screen is opened? Here’s the place to do it . . . Anyway, the ScreenConductors side of things looks like this.

Opening a Screen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public virtual void OpenScreen(IScreenSubject subject)
{
  if (subject.Matches(_screens.Active))
  {
    return;
  }

  IScreen screen = findScreenMatchingSubject(subject);

  if (screen == null)
  {
    screen = createNewActiveScreen(subject);
  }
  else
  {
    activate(screen);
  }

  _screens.Show(screen); }

Pretty slick, isn’t it? The whole code is really dense. Most of the methods involved are not more than 5 lines long. Finding the related screen for instance is just a matter of a LINQ-Query on the ScreenCollection using the Matches method as its predicate.

Finding a matching Screen
1
2
3
4
private IScreen findScreenMatchingSubject(IScreenSubject subject)
{
  return _screens.AllScreens.FirstOrDefault(subject.Matches);
}

Creation of the target screen on the other hand is just a matter of handing the ScreenFactory (which is actually just a facade to the IoC-Container of choice) to the subject, activating the created Screen and adding it to the ScreenCollection.

Creating a new Screen
1
2
3
4
5
6
7
private IScreen createNewActiveScreen(IScreenSubject subject)
{
  IScreen screen = subject.CreateScreen(_factory);
  activate(screen);
  _screens.Add(screen);
  return screen;
}

The last missing piece here is the actual activation of the Screen.

Activating a Screen
1
2
3
4
private void activate(IScreen screen)
{
  _shellService.ActivateScreen(screen);
}

This is delegated to the so called IShellService. You might ask yourself why this particular dependency exists (at least I did). The main purpose of this service is mostly the topic of registering Commands and filling up option panes related to the current Screen. This will be a post on its own, so don’t be mad at me, when I don’t cover it today. Instead I would like to take a look at another common use case:

Usecase: Closing a Screen

Now that we’ve seen how a Screen gets opened, let’s take a look at the other side of the coin, at how it’s closed.

Closing a Screen
1
2
3
4
5
6
7
public virtual void Close(IScreen screen)
{
  if (removeScreen(screen))
  {
    activateCurrentScreen();
  }
}

Most of the handling is in the removeScreen-method (btw, where does this convention of having all private methods beeing camel-cased come from? Is this some Java-exposure leaking through? ;-))

Removing a Screen
1
2
3
4
5
6
7
8
9
private bool removeScreen(IScreen screen)
{
  if (!screen.CanClose()) return false;

  _events.RemoveListener(screen);
  _screens.Remove(screen);
  _shellService.ClearTransient();
  return true;
}

It delegates the decision whether a screen can be closed to the screen and in case it can be closed, it removes the screen from the EventAggregator (_events), from the ScreenCollection (_screens) and clears its Command-registration (_shellService.ClearTransient()), before it activates the next screen becoming visible (in case there is one).

Activating the current Screen
1
2
3
4
5
6
7
8
9
private void activateCurrentScreen()
{
  IScreen screen = _screens.Active;

  if (screen != null)
  {
    activate(screen);
  }
}

Usecase: App shutdown coordination

There is another common usecase implemented by the ScreenConductor I would like to show you. This is how the whole app shutdown is coordinated. Prerequesites for this: Instances interested in beeing notified when the user tries to shut the application down, need to a) implement the IClosable interface and b) be registered at the EventAggregator. The latter is done automatically for screens by the ScreenConductor.

The IClosable interface
1
2
3
4
5
public interface ICloseable
{
  void AddCanCloseMessages(CloseToken token);
  void PerformShutdown();
}

The IClosable interface just consists of two methods. void AddCanCloseMessage(CloseToken) is called in order to get feedback from listeners whether the application is allowed to be shutdown. You can think of CloseToken as a more or less extended version of CancelEventArgs.

The CloseToken class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CloseToken
{
  private readonly List<string> _messages = new List<string>();

  public string[] Messages
  {
    get { return _messages.ToArray();
  }

  public void AddMessage(string message)
  {
    _messages.Add(message);
  }
}

The following code piece is hooked into the Closing - event of StoryTellers main window (the shell). It heavily leverages the delegate based eventing of StoryTellers EventBroker in order to interact with all interested listeners.

Shutdown as implemented in StoryTeller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public bool CanClose()
{
  var token = new CloseToken();

  _events.SendMessage(x => x.AddCanCloseMessages(token));
  bool returnValue = true;

  if (token.Messages.Length > 0)
  {
    string userMessage = string.Join("\\n", token.Messages);
    returnValue = _messageBox.AskUser(CAN_CLOSE_TITLE, userMessage);
  }

  if (returnValue)
  {
    _events.SendMessage(x => x.PerformShutdown());
  }

  return returnValue;
}

One remark to the CanClose() code: _messageBox is just a small wrapper abstraction in order to make user interaction via message prompts testable. There’s nothing really fancy behind that. I really like the way the app shutdown is implemented. In fact we’ve added something very similar in my current project. However, I’m not so sure when it comes to the question whether this particular code piece should be part of the ScreenConductor. You could argue that this method has only very limited cohesion with the rest of the ScreenConductors methods. In fact most of the stuff the ScreenConductor interacts with (ScreenCollection, Screens, ScreenFactory, ScreenSubject) isn’t touched in this method. Besides that, it’s code that client application code normally IMHO doesn’t need to or even should call. In our current app we’ve extracted this responsibillity into a separate class called the ApplicationShutdownCoordinator because of that.

Some more impressions on StoryTellers ScreenConductor

The exposed API of the ScreenConductor is pretty small, actually only 6 “core” methods and some overloads. Most of the API really shines. However, besides the already mentioned CanClose() functionality, there is another functionality which in my opinion should not be in the ScreenConductor. Can you spot it?

image

LoadHierarchy(Func<Hierarchy>)) looks a bit misplaced to me because it seems to work on a different abstraction level than the rest of the methods. It looks very application specific, while the rest of the StoryTeller APIs look very general purpose (independent from the fact whether Jeremy actually wanted to achieve this or this being just the result of applying good design practices). Same applies to one of the messages / events the ScreenConductor is registered for at the EventBroker, namely DeleteTestMessage. I don’t think it should be directly handled in the ScreenConductor.

image

A static code analysis might indicate that the ScreenConductor has too many dependencies. In fact there’re 7 direct dependencies injected into the constructor,

  • IEventAggregator
  • IScreenCollection
  • IScreenFactory
  • IApplicationShell
  • IShellService
  • IScreenObjectLocator
  • IMessageCreator

6 transient dependencies (method parameters or local scope),

  • IScreen
  • IScreenSubject
  • CloseToken
  • UserScreenActivation
  • OpenItemMessage
  • DeleteTestMessage

and 3 Message interests

  • UserscreenActivation
  • OpenItemMessage
  • DeleteTestMessage

in the ScreenConductor class. Sounds pretty heavy and like a refactoring candidate at first. However, as I mentioned earlier, the ScreenConductor is mostly a Facade with some additional coordination logic in it. When I say “some additional coordination logic” I mean this literally. ScreenConductor has just round about 250 LOC.

I’m totally ok with this. It certainly has some potential for optimization of the dependencies (IScreenObjectLocator seems to be at least partially obsolete, IApplicationShell and IShellService could be merged I guess), but even without that I consider it a really good example of strong extensible design for composite desktop apps. For me personally the ScreenConductor fills a really important gap in the p&p composite app guidance (be it CAB / SCSF or PRISM). I always had the feeling that I’m missing something there, but was unable to point out exactly what I’ve been missing. This feeling mostly came up when I added some screen activation or screen creation logic in places that didn’t felt right. Now I know why. Interestingly others observed the need for something similar as well. Having a ScreenConductor in your application makes IMHO the whole UI infrastructure a lot more approchable and easier to understand.

Some final thoughts

I left the rest of the ScreenConductors code out of this post intentionally, because if there’s one thing I’d like you to take from this post or even the complete series is that StoryTeller is a really good learning resource. I really value, what I’ve learned from the Dovetail guys while inspecting the code. I wish I had done this earlier. Good design matters. If you’re looking for a place to learn more about it, the StoryTeller codebase might just be the place for you. See you next time, when we take some time to dig into the command structure of StoryTeller …


Notifications the WPF way (I guess), Part III

Today I would like to conclude my little series about the Notification Pattern with (I guess at least for some of you) the most interesting part:

Today is all about displaying Notifications in the UI

This post will guide you through all the steps I took in order to achieve the affect I demonstrated in the introduction post. Last time I showed how I’m transfering Notifications from the ViewModel into the logical WPF tree. If you’ve not read the previous posts, please give them some minutes, because I’m not going to repeat a lot of them today. You can find them here, here and here. As always, a quick reminder:

What I’m showing is in this series is how I’ve implemented the Notification Pattern. I’m not claiming that it’s the only or the best way to do so. However, it’s the one that works very good for me.

How to get the red border effect

The red border has to be displayed when Notifications exists for a control. Technically this means that the attached property Notifications (which is defined on the ValidationBehavior class I showed in the last post) is set to a non empty NotificationCollection. We can react to this by defining a DataTrigger for this. In my own words I would describe a DataTrigger as

An in XAML defined event handler with a related criteria. When the criteria is matched the DataTrigger gets executed. When it isn’t matched any more, the DataTrigger reverts the state of the element on which it’s defined to the state before it was executed.

Sounds usable for our purpose. Think about it, we only want to show the red border, when the attached property is set to a non empty collection. If the property is reset the border needs to disappear. The only difficulty with DataTriggers we need to solve on our way is how to configure that exactly in XAML. DataTriggers can be easily set on primitives (such as string, bool, etc.) or null, but there isn’t an out of the box way for setting our criteria in XAML. However you can use a custom Converter for converting our value to a primitive “switch”.

An IValueConverter for our DataTrigger
1
2
3
4
5
6
7
8
9
10
11
12
13
[ValueConversion(typeof(NotificationCollection), typeof(bool))]
public class ContainsNotificationConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return (value != null && value is NotificationCollection && ((NotificationCollection)value).Any());
  }

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

Using this converter we can define our DataTrigger in the Style for Controls like this:

Wiring it up via XAML DataTriggers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Fx:ContainsNotificationConverter x:Key="notificationConverter" />

<Style TargetType="Control">
     <Setter Property="Fx:ValidationBehavior.IsEnabled" Value="true" />
     <Style.Triggers>
         <DataTrigger
             Binding="{Binding Path=(Fx:ValidationBehavior.Notifications),
             Converter={StaticResource notificationConverter},
             RelativeSource={x:Static RelativeSource.Self}}" Value="true">
             <Setter Property="BorderBrush" Value="Red" />
             <Setter Property="BorderThickness" Value="2" />
         </DataTrigger>
     </Style.Triggers>
 </Style>

How to display Notifications in a Tooltip

Solving the Tooltip requirement was a bit more tricky (at least for me). It took me quite some time to figure out how to do this in WPF. The solution I’m going to show uses only XAML based code.

1. Integrating the Tooltip into the DataTrigger

We simply use our DataTrigger to automatically set the tooltip of a Control in case Notifications exist.

Adding the tooltip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ToolTip x:Key="ValidationErrorTooltip" />

<Style TargetType="Control">
     <Setter Property="Fx:ValidationBehavior.IsEnabled" Value="true" />
     <Style.Triggers>
         <DataTrigger
             Binding="{Binding Path=(Fx:ValidationBehavior.Notifications),
             Converter={StaticResource notificationConverter},
             RelativeSource={x:Static RelativeSource.Self}}" Value="true">
             <Setter Property="BorderBrush" Value="Red" />
             <Setter Property="BorderThickness" Value="2" />
             <Setter Property="ToolTip" Value="{StaticResource ValidationErrorTooltip}" />
         </DataTrigger>
     </Style.Triggers>
 </Style>

Now the UI looks really crappy. The tooltip is not recognizable as one.

Horrible Tooltip

2. Using a ControlTemplate to style the Tooltip

In order to shape the appearance of the tooltip we can use XAML Styles again. You can change the whole visual appearance of a Control using Styles and ControlTemplates. The template I defined consists mostly of a DockPanel containing a Label (which provides the tooltips caption) and a TextBlock (which will later contain the Notification messages).

Adding ControlTemplates to the mix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<Style x:Key="ErrorTooltipSyle" TargetType="ToolTip">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToolTip">
                <Border BorderBrush="Black" BorderThickness="1">
                    <DockPanel>
                        <Label DockPanel.Dock="Top"
                          FontWeight="Bold"
                          Background="Red"
                          Foreground="White"
                          Content="Validation Error" />
                        <TextBlock
                          Padding="10"
                          Background="White"
                          Foreground="Black"
                          TextWrapping="WrapWithOverflow" />
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<!-- Notice the defined Style -->
<ToolTip x:Key="ValidationErrorTooltip" Style="{StaticResource ErrorTooltipSyle}" />

<Style TargetType="Control">
    <Setter Property="Fx:ValidationBehavior.IsEnabled" Value="true" />
    <Style.Triggers>
        <DataTrigger
            Binding="{Binding Path=(Fx:ValidationBehavior.Notifications),
            Converter={StaticResource notificationConverter},
            RelativeSource={x:Static RelativeSource.Self}}" Value="true">
            <Setter Property="BorderBrush" Value="Red" />
            <Setter Property="BorderThickness" Value="2" />
            <Setter Property="ToolTip" Value="{StaticResource ValidationErrorTooltip}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Our UI now looks like this.

Tooltip with ItemSource

Not as crappy as before but we’re not finished yet, because we’re not displaying Notifications yet.

3. Define Databinding on the Tooltip

Defining the Databinding was probably the hardest step I had to take. The problem is that you need to get the NotificationCollection from the Control the tooltip is displayed on. Being not a WPF pro figuring out how to do this took quite some time. Anyway, in order to get the Notification there isn’t much you need to do. The trick is to bind against the property PlacementTarget on the ToolTip class itself. This property holds the reference to the Control on which the Tooltip instance is displayed. All we need to do is to add a Binding to the Style definition that sets the DataContext of the ToolTip to the related control.

Binding the PlacementTarget to display the tooltip
1
2
3
4
5
<Style x:Key="ErrorTooltipSyle" TargetType="ToolTip">
    ...
    <Setter Property="DataContext" Value="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}" />
    ...
</Style>

The next step we need to take is setting up the Binding for our attached property Notifications. Because a NotificationCollection can contain more than one Notification I used the ItemsControl for displaying them in the content area of the tooltip.

Displaying the Notifications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<Style x:Key="ErrorTooltipSyle" TargetType="ToolTip">
  <Setter Property="DataContext" Value="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToolTip">
                <Border BorderBrush="Black" BorderThickness="1">
                    <DockPanel>
                        <Label DockPanel.Dock="Top"
                          FontWeight="Bold"
                          Background="Red"
                          Foreground="White"
                          Content="Validation Error" />
                        <TextBlock
                          Padding="10"
                          Background="White"
                          Foreground="Black"
                          TextWrapping="WrapWithOverflow">

                            <!-- This control displays our Notifications -->
                            <ItemsControl x:Name="notifications"
                                HorizontalAlignment="Stretch"
                                Margin="10"
                                VerticalAlignment="Center"
                                ItemsSource="{Binding Path=(Fx:ValidationBehavior.Notifications), Mode=OneWay}"/>

                         </TextBlock>
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Voila, our Notifications are finally displayed in the UI.

Tooltip with ControlTemplate

4. Styling the Notifications

In my initial post I showed a hyphen in front of each Notification. This is fairly easy to add, too. All you have to do is to define a DataTemplate for the Notification class and set it as the ItemTemplate of the ItemsControl we’re using.

Styling the notifications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!-- Very simple data template -->
<DataTemplate x:Key="NotificationTemplate">
    <StackPanel Orientation="Horizontal">
        <TextBlock>-</TextBlock>
        <TextBlock x:Name="notification" Text="{Binding}" />
    </StackPanel>
</DataTemplate>

<Style x:Key="ErrorTooltipSyle" TargetType="ToolTip">
  <Setter Property="DataContext" Value="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToolTip">
                <Border BorderBrush="Black" BorderThickness="1">
                    <DockPanel>
                        <Label DockPanel.Dock="Top"
                          FontWeight="Bold"
                          Background="Red"
                          Foreground="White"
                          Content="Validation Error" />
                        <TextBlock
                          Padding="10"
                          Background="White"
                          Foreground="Black"
                          TextWrapping="WrapWithOverflow">
                          <ItemsControl x:Name="notifications"
                                HorizontalAlignment="Stretch"
                                Margin="10"
                                VerticalAlignment="Center"
                                ItemsSource="{Binding Path=(Fx:ValidationBehavior.Notifications), Mode=OneWay}"

                                <!-- This uses configures our template for Notifications -->
                                ItemTemplate="{StaticResource NotificationTemplate}" />

              </TextBlock>
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

DataTemplates are also the weapon of choice if you want to display errors in a different fashion than warnings (for instance by displaying a different icon). This is where we arrived:

Tooltip finished

Closing thoughts

What I like about the current solution is that it demonstrates in a nice way how different the programming model of WPF actually is compared to WinForms. The only imperative code we have is the code that transfers Notifications from our ViewModel into the logical tree. That’s it. The rest, the complete visual appeal of the Notifications, is a separated concern. Those two things can be changed independently from each other, even by different roles in a development team (Designer/Developer). Besides that I like the way the composition based WPF model helps my application code to stay focused and clean with only minimum implementation constraints on the ViewModel itself (the INotificationSource interface). There’re certainly things to improve both in XAML and in the glue code but I consider it a good start to build on …


Notifications the WPF way (I guess), Part II

Back again to my take on the Notification pattern with WPF. Last time I talked briefly about my motivation for this little series. This time we dive more into the nuts and bolts of my example implementation.

How the ViewModel notifies the UI

I defined an interface called INotificationSource for this. This interface defines only I member which exposes a NotificationCollection. NotificationCollection is just a standard ObservableCollection<Notification> with some additional bits in it (such as retrieving a collection of Notifications for a given source). By deriving from ObservableCollection you get the CollectionChangedEvent on the collection for free.

The interface that needs to be implemented by a ViewModel
1
2
3
4
public interface INotificationSource
{
    NotificationCollection Notifications {get;}
}

In my current app I’ve got a Layer Supertype for ViewModels which implements this interface.

Glue code for transferring Notifications from the ViewModel into the logical tree

As I mentioned in the last post I’m using the Attached Behavior Pattern for transferring Notifications from the ViewModel to the related elements in the logical tree (When I say related I’m referring to the FrameworkElements bound to my ViewModel via DataBinding). The class responsible for the transfer is a DependencyObject derived class, called ValidationBehavior. This class defines two attached DependencyProperties, IsEnabled and Notifications.

Our attached validation behavior
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 public class ValidationBehavior : DependencyObject
 {
     public static readonly DependencyProperty IsEnabledProperty;
     public static readonly DependencyProperty NotificationsProperty;

     static ValidationBehavior()
     {
         IsEnabledProperty =  DependencyProperty.RegisterAttached(
                                 "IsEnabled",
                                 typeof(bool),
                                 typeof(ValidationBehavior),
                                 new FrameworkPropertyMetadata(OnValidationBehaviorEnabled));

         NotificationsProperty = DependencyProperty.RegisterAttached(
                                 "Notifications",
                                 typeof(NotificationCollection),
                                 typeof(ValidationBehavior),
                                 new PropertyMetadata(null));
     }

     public static bool GetIsEnabled(DependencyObject host)
     {
         return (bool) host.GetValue(IsEnabledProperty);
     }

     public static void SetIsEnabled(DependencyObject host, bool isEnabled)
     {
         host.SetValue(IsEnabledProperty, isEnabled);
     }

     public static NotificationCollection GetNotifications(DependencyObject host)
     {
         return (NotificationCollection)host.GetValue(NotificationsProperty);
     }

     public static void SetNotifications(DependencyObject host, NotificationCollection notification)
     {
         host.SetValue(NotificationsProperty, notification);
     }
}

The attached DependencyProperty IsEnabled is used to attach our behavior to the target element marked with the property. Notice the OnValidationBehaviorEnabled handler which is called when the value of the registered attached DependencyProperty has changed. The attached DependencyProperty Notifications will later hold the collection of Notifications extracted from the ViewModel by our attached behavior. By having the NotificationCollection as an attached property you’re able to bind against it from XAML (as we’ll see in the following post). If you recall the last post about this topic, maybe you remember that I didn’t actually set the attached property IsEnabled in the ViewModels XAML file. You could configure the behavior in the related XAML file but I didn’t want to do this for all my ViewModels. Because of this I decided to use Styles for this.

XAML styles to wire it up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- The global application class -->
<Application x:Class="Notifications.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
        <ResourceDictionary Source="Resources/Theme.xaml" />
    </Application.Resources>
</Application>

<!-- My XAML file containing the resources -->
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Fx="clr-namespace:Notifications.Fx">

    <Style TargetType="Control">
        <Setter Property="Fx:ValidationBehavior.IsEnabled" Value="true" />
    </Style>

    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}" />

</ResourceDictionary>

When the Style is applied the IsEnabled attached property will be automatically set on all elements based on that style and this brings us into the position to hook into the elements events and access the elements data. The OnValidationBehaviorEnabled handler is actually straight forward.

Attach to the target FrameworkElement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private static void OnValidationBehaviorEnabled(
    DependencyObject dependencyObject,
    DependencyPropertyChangedEventArgs args)
{
    var frameworkElement = (FrameworkElement)dependencyObject;

    // Get the DataContext from the element. Mostly this DataContext is not directly
    // set on the element but rather derived from the parents DataContext
    var notificationSource = frameworkElement.DataContext as INotificationSource;

    if (notificationSource == null)
    {
        return;
    }

    // Clear related Notifications of an element when the element
    // got the focus.
    frameworkElement.GotFocus += ClearNotificationOnFocus;

    // Hook into the CollectionChanged event of the NotificationCollection.
    // I'm using a closure here in order to capture the FrameworkElement.
    notificationSource.Notifications.CollectionChanged += (sender, collectionChangedArgs) =>
    {
        var notifications = GetNotifications(notificationSource, frameworkElement);

        SetNotification(
            frameworkElement,
            notifications);
    };
}

The anonymous event handler registered for the CollectionChangedEvent tries to get the collection of Notifications for the FrameworkElement.

Extracting the notifications for a particular element
1
2
3
4
private static NotificationCollection GetNotifications(INotificationSource notificationSource, FrameworkElement frameworkElement)
{
    return notificationSource.Notifications.AllNotificationsFor(frameworkElement.Name);
}

As you can see this particular piece of code has a little quirk right now. It relies on the convention / assumption that the property on the ViewModel and the bound FrameworkElement share the same name. It was the easiest thing to do. It would also be easy to introduce another attached property for this in order to specify the name of the related ViewModel property. However this wouldn’t be 100% DRY because you’re most likely going to specify the property via the Binding MarkupExtension, too. I’m open to suggestions of how this correlation can be done better. The last missing code piece is the handler which clears the Notification when it gets focus. It simply sets the attached Notification property to null.

Resetting a notification on focus
1
2
3
4
5
private static void ClearNotificationOnFocus(object sender, RoutedEventArgs e)
{
    var elementWithNotification = (FrameworkElement)e.OriginalSource;
    elementWithNotification.SetValue(NotificationProperty, null);
}

Closing thoughts

I hope you’re getting a feeling for what I wanted to show with this little post series. Today I talked mostly about how Notifications can be transfered from the ViewModel into the WPF tree. While the code currently has some pieces in it that imho should be refactored (correlation of the Notifications, CollectionChangedEvent currently reloads all Notifications), I hope you saw in this post that it’s relatively easy to add such an ability to your app infrastructure without a) having a base class constraint b) a lot of imperative code and c) doing a lot of configuration. The next post will conclude this little series mostly with XAML stuff. We’re going to cover how to combine the different tools (DataTrigger, DataTemplates, ControlTemplates, Converter) that WPF offers in order to fire up a Tooltip containing all Notifications for an element.

CU next time …


Notifications the WPF way (I guess), Part I

Update 2.11.2009: I removed the DependencyObject and DependencyProperty references from the ViewModel. The solution works fine without them.

This is the start of a small mini series about how I would currently approach the Notification Pattern in a WPF application, using the default WPF practices and patterns. Think about it as a step by step guide for using DataBinding, Control-Templates, Styles, Resource-Inheritance, Converters and the Attached-Behavior-Pattern for displaying Notifications in the WPF-UI. (I guess most of this is also doable in Silverlight too, but I’ve never done anything with SL so I can’t say for sure). I’ve also prepared a little bit of sample code for this topic which will be downloadable soon.

First, some cautious warnings

I’m by no means a WPF-expert. I’m still in the learning phase. So, if there are more obvious or intuitive solutions to the problem, or I’m plain wrong about this, feel free to comment. I’m sure there is A LOT room for improvement.

What I’ve left out intentionally

I tried to strip everything unnecessary for the scope of the post from the code. This includes for instance IoC, Convention over Configuration, Code-Contracts, Expression-based Databinding setup and some base class or extension refactorings. Don’t get me wrong, I absolutely value those elements, but I wanted the example to be as easy as possible while being somewhat useful for a ‘real world’ application. The code might look a bit raw at at some edges because of this. So please keep that in mind before throwing with stones ;-)

Some other prerequesites

A while back I wrote a post about implementing the Notification-pattern using System.Componentmodel.DataAnnotations. It demonstrates the implementation of a generic validator based on the DataAnnotation attributes. Besides that, this post about the Attached-Behavior-Pattern will also be useful for this mini-series. Please give them a short visit if you haven’t read them yet.

The example scenario

The scenario I’m going to use for the example is a very simple sign up form. It contains two input fields for username / email and a ‘sign-up’ button. It looks like this.

image

Rules associated with the fields are:

  1. Username is required and must at least be 5 characters long.
  2. Email is required and must contain a valid email address.

If any of the rules is broken, the related element should be visually highlighted …

image

… and when you hover over the element you’ll get a detailed description of the error from a tooltip.

image

I’m using the PresentationModel / MVVM pattern for the UI since it seems to be the default UI pattern in WPF.

This is how I would like my SignUpView to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<Window x:Class="Notifications.SignUpView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Grid.Column="1"
            Grid.Row="1"
            Header="Sign up"
            BorderThickness="2"
            VerticalAlignment="Center"
            HorizontalAlignment="Center"
            MaxWidth="300"
            MaxHeight="600">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label
                    Content="Username:"
                    VerticalAlignment="Bottom"
                    Margin="10,0,10,0"
                    Grid.Row="0"
                    Grid.Column="0" />
                <Label
                    Content="Email:"
                    VerticalAlignment="Bottom"
                    Margin="0,0,10,0"
                    Grid.Row="0"
                    Grid.Column="1" />
                <TextBox
                    Name="Username"
                    MinWidth="100"
                    MaxHeight="30"
                    Margin="10,0,10,10"
                    Grid.Row="1"
                    Grid.Column="0"
                    TabIndex="0"
                    Text="{Binding Path=Username, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
                <TextBox
                    Name="Email"
                    MinWidth="100"
                    MaxHeight="30"
                    Margin="0,0,10,10"
                    Grid.Row="1"
                    Grid.Column="1"
                    Text="{Binding Path=Email, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
                    TabIndex="1" />
                <Button
                    MaxHeight="30"
                    Grid.Row="1"
                    Margin="0,0,10,10"
                    Grid.Column="2"
                    Content="Sign up!"
                    TabIndex="3"
                    Command="{Binding Path=SignUpCommand, Mode=OneWay}" />
            </Grid>
        </GroupBox>
    </Grid>
</Window>
This is how I would like my SignUpViewModel to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class SignUpViewModel : INotificationSource
{
    private readonly NotificationCollection _notifications;
    private readonly DelegateCommand _signUpCommand;
    private readonly ISignUpService _signUpService;
    private readonly IValidator<SignUpViewModel> _validator;

    #region Constructors

    public SignUpViewModel(IValidator<SignUpViewModel> validator, ISignUpService signUpService)
    {
        _validator = validator;
        _signUpService = signUpService;
        _notifications = new NotificationCollection();
        _signUpCommand = new DelegateCommand(TrySignUp);
    }

    #endregion

    #region Properties

    [Required(ErrorMessage = "Field 'Username' is missing")]
    [MinimumStringLength(5)]
    public string Username
    {
        get;
        set;
    }

    [Required(ErrorMessage = "Field 'Email' is missing")]
    [MinimumStringLength(5)]
    public string Email
    {
        get;
        set;
    }

    public ICommand SignUpCommand
    {
        get { return _signUpCommand; }
    }

    public NotificationCollection Notifications
    {
        get { return _notifications; }
    }

    #endregion

    #region Private methods

    private void TrySignUp()
    {
        if (!IsValid())
        {
            return;
        }

        _signUpService.TrySignUp(Username, Email);
    }

    private bool IsValid()
    {
        Notifications.Clear();

        _validator.Validate(this, Notifications);

        return Notifications.ContainsErrors;
    }

    #endregion
}

Did you notice it?

There is NO CODE in the View (Xaml and code behind) or the ViewModel which displays the Notifications.There’s also no base class for View or ViewModel where the code might be. What’s there on the other hand is only a collection of Notifications hanging of the ViewModel which is filled by the Validator. You might yourself now ask: Where is the damn glue code? Yeah I know dumb question because I answered it mostly in the introduction of the post. The interesting thing is that it isn’t a single location. As you will see the responsibilities for achieving the effect are separated between several components.

In the next posts we’re going to take a look at

  • how to use the Attached-Behavior-Pattern together with Styles and resource based inheritance in order to match the Notification (s) from the ViewModel to the related FrameworkElements in the logical WPF tree.
  • how to use a DataTrigger on an Attached Property in order to setup the Tooltip and showing the red border.
  • how to bind the Tooltip correctly to the related Notification(s).

I hope I made you at least a bit curious …