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
1234
publicinterfaceICommand{voidExecute();}
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
123456
publicenumCommandStatus{Enabled,//visible and enabledDisabled,//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.
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.
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.
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).
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:
We packaged our conventions for the project into a single composite convention. This includes the easier mappings ala IFoo – Foo, 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?
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
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.
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 ;-)
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
Although I’m still not 100% sure that I “get” what the Twitter fuzz is all about, I decided to give it a try and use it for a while, in order
to form my opinion about it. If you’re interested to stay in touch via Twitter, here’s my Url:
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:
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 …
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.
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?
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.
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.
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.
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.
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.
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? ;-))
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).
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 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 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.
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?
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.
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 …
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”.
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.
Now the UI looks really crappy. The tooltip is not recognizable as one.
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).
<Stylex:Key="ErrorTooltipSyle"TargetType="ToolTip"><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="ToolTip"><BorderBorderBrush="Black"BorderThickness="1"><DockPanel><LabelDockPanel.Dock="Top"FontWeight="Bold"Background="Red"Foreground="White"Content="Validation Error"/><TextBlockPadding="10"Background="White"Foreground="Black"TextWrapping="WrapWithOverflow"/></DockPanel></Border></ControlTemplate></Setter.Value></Setter></Style><!-- Notice the defined Style --><ToolTipx:Key="ValidationErrorTooltip"Style="{StaticResource ErrorTooltipSyle}"/><StyleTargetType="Control"><SetterProperty="Fx:ValidationBehavior.IsEnabled"Value="true"/><Style.Triggers><DataTriggerBinding="{Binding Path=(Fx:ValidationBehavior.Notifications), Converter={StaticResource notificationConverter}, RelativeSource={x:Static RelativeSource.Self}}"Value="true"><SetterProperty="BorderBrush"Value="Red"/><SetterProperty="BorderThickness"Value="2"/><SetterProperty="ToolTip"Value="{StaticResource ValidationErrorTooltip}"/></DataTrigger></Style.Triggers></Style>
Our UI now looks like this.
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
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.
<Stylex:Key="ErrorTooltipSyle"TargetType="ToolTip"><SetterProperty="DataContext"Value="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}"/><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="ToolTip"><BorderBorderBrush="Black"BorderThickness="1"><DockPanel><LabelDockPanel.Dock="Top"FontWeight="Bold"Background="Red"Foreground="White"Content="Validation Error"/><TextBlockPadding="10"Background="White"Foreground="Black"TextWrapping="WrapWithOverflow"><!-- This control displays our Notifications --><ItemsControlx: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.
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.
<!-- Very simple data template --><DataTemplatex:Key="NotificationTemplate"><StackPanelOrientation="Horizontal"><TextBlock>-</TextBlock><TextBlockx:Name="notification"Text="{Binding}"/></StackPanel></DataTemplate><Stylex:Key="ErrorTooltipSyle"TargetType="ToolTip"><SetterProperty="DataContext"Value="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}"/><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="ToolTip"><BorderBorderBrush="Black"BorderThickness="1"><DockPanel><LabelDockPanel.Dock="Top"FontWeight="Bold"Background="Red"Foreground="White"Content="Validation Error"/><TextBlockPadding="10"Background="White"Foreground="Black"TextWrapping="WrapWithOverflow"><ItemsControlx:Name="notifications"HorizontalAlignment="Stretch"Margin="10"VerticalAlignment="Center"ItemsSource="{Binding Path=(Fx:ValidationBehavior.Notifications), Mode=OneWay}"<!--ThisusesconfiguresourtemplateforNotifications--> 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:
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 …
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
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.
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
12345678910111213141516171819202122
<!-- The global application class --><Applicationx:Class="Notifications.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Application.Resources><ResourceDictionarySource="Resources/Theme.xaml"/></Application.Resources></Application><!-- My XAML file containing the resources --><ResourceDictionaryxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:Fx="clr-namespace:Notifications.Fx"><StyleTargetType="Control"><SetterProperty="Fx:ValidationBehavior.IsEnabled"Value="true"/></Style><StyleTargetType="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.
privatestaticvoidOnValidationBehaviorEnabled(DependencyObjectdependencyObject,DependencyPropertyChangedEventArgsargs){varframeworkElement=(FrameworkElement)dependencyObject;// Get the DataContext from the element. Mostly this DataContext is not directly// set on the element but rather derived from the parents DataContextvarnotificationSource=frameworkElement.DataContextasINotificationSource;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)=>{varnotifications=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
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.
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.
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.
Rules associated with the fields are:
Username is required and must at least be 5 characters long.
Email is required and must contain a valid email address.
If any of the rules is broken, the related element should be visually highlighted …
… and when you hover over the element you’ll get a detailed description of the error from a tooltip.
I’m using the PresentationModel / MVVM pattern for the UI since it seems to be the default UI pattern in WPF.
publicclassSignUpViewModel:INotificationSource{privatereadonlyNotificationCollection_notifications;privatereadonlyDelegateCommand_signUpCommand;privatereadonlyISignUpService_signUpService;privatereadonlyIValidator<SignUpViewModel>_validator;#region ConstructorspublicSignUpViewModel(IValidator<SignUpViewModel>validator,ISignUpServicesignUpService){_validator=validator;_signUpService=signUpService;_notifications=newNotificationCollection();_signUpCommand=newDelegateCommand(TrySignUp);}#endregion#region Properties [Required(ErrorMessage = "Field 'Username' is missing")] [MinimumStringLength(5)]publicstringUsername{get;set;} [Required(ErrorMessage = "Field 'Email' is missing")] [MinimumStringLength(5)]publicstringEmail{get;set;}publicICommandSignUpCommand{get{return_signUpCommand;}}publicNotificationCollectionNotifications{get{return_notifications;}}#endregion#region Private methodsprivatevoidTrySignUp(){if(!IsValid()){return;}_signUpService.TrySignUp(Username,Email);}privateboolIsValid(){Notifications.Clear();_validator.Validate(this,Notifications);returnNotifications.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).