Introduction to Attached Behaviors in the context of MVVM

image 

There is also a great and yet simple article that shows how attached behaviors is used to capture an element’s right-click event and Bind it to a MVVM ICommand property.

Introduction to Attached Behaviors in the context of MVVM

Download demo project

For example, suppose that the user searches through a TreeView for an item whose display text matches a user-defined search string. When the search logic finds a matching item, the matching ViewModel object will have its IsSelected property set to true. Then, via the magic of data binding, the TreeViewItem associated with that ViewModel object enters into the selected state (i.e., its IsSelected property is set to true, too). However, that TreeViewItem will not necessarily be in view, which means the user will not see the item that matches their search string. So how can we have the TreeViewItem brought into view when the ViewModel determines that it is in the selected state.

The ViewModel objects have no idea that a TreeViewItem exists, and is bound to them, so it does not make sense to expect the ViewModel objects to bring TreeViewItems into view. The question becomes, now, who is responsible for bringing a TreeViewItem into view when the ViewModel forces it to be selected?

Attached Behaviors

The solution to the problem explained above is to use an attached behavior. Attaching a behavior to an object simply means making the object do something that it would not do on its own.

The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it (e.g. TreeViewItem’s Selected event) and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.

So how do we attach the behavior to every TreeViewItem in the TreeView? 
By adding a Setter to the Style applied to every TreeViewItems
<TreeView.ItemContainerStyle>
  <Style TargetType="{x:Type TreeViewItem}">
    <!--
    This Setter applies an attached behavior to all TreeViewItems.
    -->
    <Setter 
      Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" 
      Value="True" 
      />

Introduction to Attached Behaviors in WPF – CodeProject

Does MVVM deserve the hype?

Ah, MVVM! MVVM is the rock star who packs the house at every XAML event. It’s in books, blog posts, and podcasts. You can’t swing a dead laptop without hitting someone who is spouting about the virtues of model-view-viewmodel. With so much hype, there’s bound to be backlash.

Does MVVM deserve the hype?

Short answer – no.

An Alternative?

You’ve got a complex UI with lots of rules, and you reject the MVVM best practice crap the whiteboarding architect is jamming down your throat. You’re gonna be … pragmatic!

More …

Creating Silverlight Composite Application using Prism – Screencasts

image updated

  1. An Intro to Composite Applications – Eric Mork

    Prism can be thought of as a set of libraries that help Silverlight applications be scalable and testable. It has a number of features (modularity, view regions and commanding) that help with this. This guide shows you how to get started writing a Prism application in Silverlight. It shows how to use the bootstrappers, modules, catalogs, regions and commanding.

  2. How Commanding Works in Prism and MVVM– Eric Mork

    Prism Commanding allows designers/develops to specify, in XAML, events that fire back into the View Model/Presenter. Imagine this: the user hovers a mouse over a Silverlight control. Commanding allows that action to be bound to a method (more specifically, a delegate) in the ViewModel. The View Model then handles that action. This Commanding support overcomes a deficiency (lack of ICommand implementation) in Silverlight that makes proper MVVM implementation difficult. If you’re using MVVM, Commanding is a must. That can take the form of a home-grown solution, Prism or any of a number of other libraries: Caliburn, Silverlight.FX, etc. In Prism Commanding, the Commands are implemented as attached properties. This video shows how to use the existing command (button click), handle command parameters, use the CanExecute functionality, and create new commands.

  3. Eventing in Prism – Loosely Coupled Talking – Eric MorkPrism allows us to have modular and loosely coupled applications, but how do these loosely coupled pieces communicate? That’s where Eventing and the EventAggregator come in: they provide communication channels. A way that the separate pieces of the application can safely talk back and forth. Eventing also has extra goodies (thread preference, weak references) that are built on the lessons learned from past technologies (like CAB). All around, it’s a great helper for any Silverlight/Prism (or WPF) application.
  4. Modularity – Testing, Module Catalog and Unity in Prism – Eric Mork

    Modularity allows applications to be broken down into discrete pieces. This allows for easier testing, better maintainability and the ability to distribute an application across multiple teams. This video explores the modularity support in Prism. The first part of the video covers Unity and Unit Testing. Inversion of Control using Dependency Injection and Service Location are both covered. The second part of the video details modules and how they’re loaded by the Module Catalog.

  5. Regions in Prism Video – Eric Mork

    Regions in Prism are kind of like Master Pages. They allow us to have master and sub-views. If you’re interested in composing views separately and then bringing them together in the running application, Regions are for you. As with all of the things in Prism, Regions are a part of the buffet. You can use them or not at your discretion.

image

In this 4 part series, Bob Brumfield and Erwin van der Valk from patterns and practices shows you how to build a modular application using the recently released Composite Application Guidance for WPF and Silverlight – February 2009 (also known as Prism V2). Source code.

  1. Creating a shell and modules

  2. In this screencast, you will see how to divide an application into modular pieces and how to recombine them again in a shell.

  3. Visual Composition

  4. This webcast demonstrates how to create placeholders for views and how to load views into them.

  5. Implementing views and services

  6. This webcast demonstrates how to create a view using the Model – View – ViewModel pattern, and how to create and inject Services into your classes by using the Unity Dependency Injection Container.

  7. Decoupled Communication

  8. This webcast demonstrates how to communicate between the different modules.

    Click the links above to watch the screencast.

    Also, from Prism Codeplex – Learn about Prism through videos and blogs Learn Prism

TriggerAction driven command execution with zero code behind

image

The new Behavior-based trigger system (which works in Silverlight and WPF) opens the door for custom Trigger Actions. Now that we have custom Trigger Actions, we will be able to create an ExecuteCommandAction that allows you to invoke a Command from any trigger.

What’ll we be doing is creating an ExecuteCommandAction that we can trigger using any Blend trigger, this action will be bound to a ICommand exposed by the ViewModel.

In the current version of Silverlight standard behaviors don’t support Binding, there is a work around discussed earlier on this blog by PeteBlois using BindingListeners and exposing Bindings rather than ICommand.

public class ExecuteCommandAction : TriggerAction<FrameworkElement>

{

private readonly BindingListener commandListener;

private readonly BindingListener commandParameterListener;

Read more –> http://compiledexperience.com/blog/posts/Blendable-MVVM-Commands-and-Behaviors

And here –> http://azurecoding.net/blogs/brownie/archive/2009/04/06/blend-behaviors-ftw.aspx

View-First(Xaml) vs ViewModel-First(DI via constructor)

image

How do you create Views and ViewModels.  The two approaches I hear most often are:

  • View-First: The View has a relationship to its ViewModel(usually through data binding).
  • ViewModel-First: The ViewModel creates the view (usually through an IoC container).

In View-First, it is usually is exemplified in XAML like so:

<UserControl x:Class="MVVM.Client.Views.GameView"
             ...
             xmlns:data="clr-namespace:MVVM.Client.Data;assembly=MVVM.Client.Data">
  <UserControl.Resources>
    <data:GamesViewModel x:Key="TheViewModel" />
  </UserControl.Resources>
  <Grid DataContext="{Binding Path=Games, Source={StaticResource TheViewModel}}">
  ...
  </Grid>
</UserControl>

In ViewModel-First, it is usually implemented using a Inversion of Control container (e.g. Unity, Ninject, Spring, etc.). This way the ViewModel can request the interface (in the constructor) for the View it expects:

public MyViewModel
{
  public MyViewModel(IMyView view)
  {
  }
}

In both of these methods it presents a sticky-ness of the view to the view-model. Also, both of these imply a one-to-one relationship which while the common case, is not the always case.

Shaw Wildermuth has come up with another pattern called  “Marriage”.

public interface IView
{
  void ApplyViewModel(object viewModel);
}

IView view = theContainer.Resolve<IGameView>();
IViewModel vm = theContainer.Resolve<IGameViewModel>();
view.ApplyViewModel(vm);

Read more -> Shawn Wildermuth – Which came first, the View or the Model?