Introduction

When we create LOB (Line-of-business) applications, we use to develop them in a modular way, to satisfy many requisites:

  • The application is sold by modules – the customer can buy the sales module, but not the industrial one.
  • The application can be developed by separated teams – each team develops an independent module.
  • The modules are only loaded when the user needs it.
  • The application doesn’t need to be completely redeployed when a module changes
  • We can create new modules and add them to the application with no need to change the other modules.

To create a modular application we must create a custom infrastructure that needs lots of work and can introduce bugs to the system

.Net 4.0 brought a new resource that allows us to create modular and extensible applications: MEF (Managed Extensibility Framework). This is a framework to create extensible apps and it is thoroughly tested – Visual Studio uses MEF for its extension system: when you use a Visual Studio add-in, you are using MEF.

Introduction to MEF

Before developing out modular application, we will see how to use MEF. To use it, you must include a reference to System.ComponentModel.Composition. After adding the reference we must tell to the program which are the parts that must be combined: on one side, we have the exported classes, the modules that will be added to the main module, that will fit in the imported parts.

To do this association and the module discovery, combining the exported parts to the imported ones we use Containers. They will discover the modules and will combine the exported to the imported parts. Containers can use catalogs to find the application parts. Does this seem difficult? Let’s see how does it work in the real world.

Create a new console project and add a reference to System.ComponentModel.Composition. Create a new class and call it Menu:

public class Menu
{
    private Module _module;
    public void OptionList()
    {
       Console.WriteLine(_module.Title);
    }
}

We need to create the Module class:

public class Module
{
    public Module()
    {
        Title = "Customers";
    }
    public string Title { get; set; }
}

Now we need to declare what will be exported and where this exported class will fit, using the [Import] and [Export] attributes:

public class Menu
{
    [Import]
    private Module _module;

    public void OptionList()
    {
       Console.WriteLine(_module.Title);
    }
}

[Export]
public class Module
{
    public Module()
    {
        Title = "Customers";
    }
    public string Title { get; set; }
}

Note that the _module field in the Menu class is private – this doesn’t affect the composition. Now, we need to create our container and let it do its magic. In Program.cs put the following code:

static void Main(string[] args)
{
    var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
    var container = new CompositionContainer(catalog);
    var menu = new Menu();
    container.ComposeParts(menu);
    menu.OptionList();
    Console.ReadLine();
}

We have created an AssemblyCatalog (that searches the parts in the assembly – in our case, in the current assembly), then created the container that composes the parts after the menu is created. When the menu.OptionList() method is called, the module’s title is listed:

fig1

Getting more than one component

Now, you will say: but we have only one module listed. How do we do to have more than one? We must create a new interface IModule:

public interface IModule
{
    string Title { get; set; }
}

Our class will implement this interface and the export will tell that we are exporting the IModule interface:

[Export(typeof(IModule))]
public class Module : IModule
{
    public Module()
    {
        Title = "Customers";
    }

    public string Title { get; set; }
}

In order to match the parts, we must say that the imported part is also of IModule type:

public class Menu
{
    [Import]
    private IModule _module;
    public void OptionList()
    {
       Console.WriteLine(_module.Title);
    }
}

We execute the application and see that everything works like before. We can add the new modules:

[Export(typeof(IModule))]
public class Customer : IModule
{
    public Customer()
    {
        Title = "Customers";
    }
    public string Title { get; set; }
}

[Export(typeof(IModule))]
public class Product : IModule
{
    public Product()
    {
        Title = "Products";
    }
    public string Title { get; set; }
}

[Export(typeof(IModule))]
public class Supplier : IModule
{
    public Supplier()
    {
        Title = "Suppliers";
    }
    public string Title { get; set; }
}

We execute the application and… we get a ChangeRejectedException exception:
More than one export was found that matches the constraint: ContractName IntroMEF.IModule“. MEF is complaining that we have many classes that export IModule.

The [Import] attribute allows only one export for the same interface. If there is more than one, this exception is thrown. When we want that many classes export the same interface, we must use the [ImportMany] attribute. To allow importing all the classes, we need to change the import a little, changing the attribute to [ImportMany] and the property type of the _module
field to IEnumerable<IModule>:

public class Menu
{
    [ImportMany]
    private IEnumerable<IModule> _modules;

    public void OptionList()
    {
        foreach (var module in _modules)
        {
           Console.WriteLine(module.Title);
        }
    }
}

We also changed OptionList to list all the modules. Now, when we execute the application, all the modules are found and listed:

fig2

Working with modules in different assemblies

You may be thinking: “this is easy to do – everything is in the same assembly. Doesn’t MEF allow modular and extensible apps?”. All the magic is in the container and in the catalog. We have  reated an AssemblyCatalog pointing to the current assembly, but we could do the same thing pointing to another assembly. You will answer: “this is still easy, I can add a reference to the other assembly where the modules are located. Where is the magic?”.

AssemblyCatalog is not the only catalog that we can use. We can use other catalog types, like the DirectoryCatalog, that finds parts in assemblies located in a specified folder.

Let’s change our project: in the solution, create a Portable Class Library and give it the name of IntroMEF.Interfaces. Choose the desired frameworks (use Framework 4.0 or higher) and delete the Class1.cs file. Add a new interface and put there the IModule interface, removing it from the main project. On the main project, add a reference to the interface project.

Create a new Class library project and give it the name of IntroMef.Modules. Add a reference to System.ComponentModel.Composition and remove the Class1.cs file. Add a
reference to IntroMef.Interfaces and move the classes Customer, Product and Supplier to the new project.

Now we need to tell that our parts are not only in the current assembly, but they can also be found in the current folder. For that we must compose two catalogs: one for the current assembly (for the imported parts) and another for the folder (for the exported parts). We will use an AggregateCatalog to compose both catalogs:

static void Main(string[] args)
{
    var catalog = new AggregateCatalog(
        new AssemblyCatalog(Assembly.GetExecutingAssembly()),
        new DirectoryCatalog("."));
    var container = new CompositionContainer(catalog);
    var menu = new Menu();
    container.ComposeParts(menu);
    menu.OptionList();
    Console.ReadLine();
}

 

We execute our application and nothing happens – no module is listed. That is due to the fact that we haven’t copied the modules assembly to the folder where the executable is located. Copy the assembly IntroMef.Modules to the executable folder, open a command window and execute the application again. Now the modules are recognized.

fig3

We didn’t need to add any references to the main project in the module library nor add a reference to the library in the main project. All we had to do is to copy the file to the executable folder. MEF found the modules when the assembly file was in the correct folder.

Creating a WPF project with MEF

Now you may be thinking: “that’s great, but I don’t create any console projects – how do I do a modular project using WPF?”. The answer is, in the same way we create a console application. To show that I am not lying, we will create a WPF project.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="120" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <ListBox Grid.Column="0" ItemsSource="{Binding Modules}" 
             DisplayMemberPath="Title" x:Name="LbxMenu"/>
    <ContentControl Grid.Column="1" Content="{Binding ElementName=LbxMenu, 
        Path=SelectedItem.Content}" />
</Grid>

We are adding a grid with two columns. In the first one we will add the found modules and in the second one, the contents for the selected module.  To make it work, we must have two properties in every module, Title, with the module’s title and Content, a UserControl with the contents of that module.

We need to create an interface for the modules. We will do in the same way we did before, creating a new library. Create a class library and name it WPFMef.Interfaces. Add the references to PresentationCore and WindowsBase. Remove the Class1.cs file and add a new interface IModule:

public interface IModule
{
    string Title { get; }
    UIElement Content { get; } 
}

Then create a new class library for the modules. Add a new class library and name it WPFMef.Modules. Add the references to WPFMef.Interfaces, System.ComponentModel.Composition, System.Xaml, PresentationCore, PresentationFramework and WindowsBase. Create the exported classes:

[Export(typeof(IModule))]
public class Customer : IModule
{
    public string Title
    {
        get { return "Customers"; }
    }

    public UIElement Content
    {
        get { return new CustomerList(); }
    }
}

[Export(typeof(IModule))]
public class Product : IModule
{
    public string Title
    {
        get { return "Products"; }
    }

    public UIElement Content
    {
        get { return new ProductList(); }
    }
}

[Export(typeof(IModule))]
public class Supplier : IModule
{
    public string Title
    {
        get { return "Suppliers"; }
    }

    public UIElement Content
    {
        get { return new SupplierList(); }
    }
}

The next step is to create the views that will be shown when the option is selected. Create three UserControls with a content similar to this one:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Customer List" HorizontalAlignment="Center" 
               VerticalAlignment="Center" FontSize="18"/>
    <ListBox x:Name="List" Grid.Row="1"/>
</Grid>

On the constructor of the view, add this code to add items to the ListBox:

public CustomerList()
{
    InitializeComponent();
    List.ItemsSource = Enumerable.Range(1, 100)
        .Select(n => "Customer " + n);
}

We have added a simple window that shows “Customer 1” to “Customer 100”, just to show what can be done. Our module library is finished.

Go back to the main project, add the references to the library WPFMef.Interfaces and to System.ComponentModel.Composition. Create a new class and give it the name of  MainViewModel. We will add there the code to initialize the container and the Modules property:

public class MainViewModel
{
    [ImportMany]
    public IEnumerable<IModule> Modulos { get; set; }

    public MainViewModel()
    {
        var catalog = new AggregateCatalog(
            new AssemblyCatalog(Assembly.GetExecutingAssembly()),
            new DirectoryCatalog("."));
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

We only need to associate the ViewModel to the View. In MainWindow.xaml.cs, add the following code:

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainViewModel();
}

The project is ready and can be executed. When we execute it, we don’t see anything in the window. We forgot to copy the assembly with the modules again. Just copy the assembly to the executable folder and run the program again. Yesssss!

fig4

The data is shown when we select an option the content view at the right is changed.

If you don’t want to copy the project manually, you can change the project options, changing the output path for the modules, pointing to the executable path:

fig5

Conclusions

As you can see, MEF allows creating modular applications in an easy way that allows expanding our projects just by copying the dlls with the new modules. That works the same way in Windows Forms, WPF, Silverlight, Asp.Net and even Windows 8 (using NuGet). You have a standard way to create plug-ins that are not coupled, allow development done by many teams and adding or fixing modules with no need to recompile the whole project.

The full source code for this article is available in https://github.com/bsonnino/IntroMefEn and https://github.com/bsonnino/WPFMefEn

 

Introduction

In the previous article, “Testing the untestable with Fakes”, I have shown how to create unit tests for the legacy code that didn’t allow tests. With these tests in place we can give a step further to restructuring our code: using best practices on our project, creating code that can be easily maintainable in the future.

In this article we will restructure our code to use the MVVM pattern and Dependency injection. We will use here Unity, a framework created by Microsoft Patterns & Practices, for dependency injection.

Project architecture

Our project had all the code in code-behind and that makes creating tests a difficult task. Besides, that, it had a dependency on DateTime, that makes almost impossible to create reproducible tests.

The first step is to separate the model and the business rules from the view layer. This is done with the MVVM (Model-View-ViewModel) pattern. This pattern separates the presentation layer (View) from the data model (Model) using a binding layer, named ViewModel.

This design pattern makes extensive use of DataBinding in WPF/Silverlight/Windows Phone/Windows 8 and was created on 2005 by John Gossman, a Microsoft Architect on Blend team. If you want more information about this design pattern, you can check Josh Smith’s article on MSDN Magazine,  http://msdn.microsoft.com/en-us/magazine/dd419663.aspx.

The  ViewModel  is a class that implements the INotifyPropertyChanged interface:

public interface INotifyPropertyChanged
{
  event PropertyChangedEventHandler PropertyChanged;
}

It has just one event PropertyChanged that is activated when there is a change in a property. The Data binding mechanism present in WPF (and in other XAML platforms) subscribes this event and updates the view with no program intervention. So, all we need to do is to create a class that implements INotifyPropertyChanged and call this event when there is a change in a property to WPF update the view.

The greatest advantage is that the ViewModel is a normal class and doesn’t have any dependency on the view layer. That way, we don’t need to initialize a window when we test the ViewModel.

Creating the ViewModel

The first step for restructuring the program is to create the ViewModel. It is completely independent from the current project and doesn’t interfere with it.

We will use the same project that we’ve used in the previous article. Create a folder and name it ViewModel. In it, add a new class and name it MainViewModel:

class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] 
        string propertyName = null)
    {
        if (PropertyChanged != null) 
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Note that we’ve used the CallerMemberName attribute, from C# 5.0. It allows that the parameter propertyName from method OnPropertyChanged be filled with the name of the property that has called it, if we leave it blank. That means that if we have a property named TextData and do something like this:

public string TextData
{
    get { return _textData; }
    set
    {
        _textData = value;
        OnPropertyChanged();
    }
}

The compiler will fill the parameter with “TextData”, with no need that we explicitly fill it. This is excellent when we change the name of a property: if we had to pass the name for the OnPropertyChanged method and we forgot to change the parameter name, we would not have the change of the UI. Using the CallerMemberName atribute, this doesn’t happen.

Create a new property TextData, like we did above. Now, let’s create tests for this class. Go back to the test project and create a new class, calling it MainViewModelTests.cs. There, create a new test:

[TestClass]
public class MainViewModelTests
{
    [TestMethod]
    public void CreateMainViewModel_TextDataShouldHaveText()
    {
        var viewModel = new MainViewModel();
        Assert.AreEqual(
          "The current date is 01/01/2013 (Tuesday)", viewModel.TextData);
    }
}

When we execute this test, it doesn’t pass, because we didn’t create any code for assigning TextData.

We must create the code for the test to pass. Create the constructor of the MainViewModel class:

public MainViewModel()
{
    _textData = string.Format("The current date is {0:d} ({0:dddd})", 
       new DateTime(2013,1,1));
}

The test passes. We now refactor the code, creating a GetTextDate method:

public MainViewModel()
{
    _textData = GetTextDate();
}

private static string GetTextDate()
{
    return string.Format("The current date is {0:d} ({0:dddd})", 
      new DateTime(2013,1,1));
}

Our method is only valid for 1/1/2013. We must create another test for the other dates:

[TestMethod]
public void CreateMainViewModel_Date01022013_TextDataShouldHaveText()
{
    var viewModel = new MainViewModel();
    Assert.AreEqual("The current date is 01/02/2013 (Wednesday)", 
      viewModel.TextData);
}

This new test doesn’t pass. We need to go deeper – we need to change our program to retrieve the current date, but our test won’t work anymore (and won’t be reliable, as the date changes every day J), unless we use Fakes again. As we said before, this is not recommended. We need to remove the dependency of DateTime.

According to the book “Beautiful code”,  “all problems in computer science can be solved by another level of indirection”. That’s what we will do, create a level of indirection, an interface IDateTimeProvider, which will provide our dates. Create a folder and name it Interfaces and create a new interface IDateTimeProvider in it:

public interface IDateTimeProvider
{
    DateTime Now { get; } 
}

Implement this interface in the class SystemDateTimeProvider:

public class SystemDateTimeProvider : IDateTimeProvider
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

We will pass this interface to the ViewModel using the Constructor Injection technique: we pass the interface to the constructor of the class and the interface is responsible for providing the current date. When we want the real data, we use the SystemDateTimeProvider class and when we want to test the code, we use a fake class created only for that.

The constructor of MainViewModel is changed to receive the new interface:

private readonly IDateTimeProvider _dateTimeProvider;

public MainViewModel(IDateTimeProvider dateTimeProvider)
{
    _dateTimeProvider = dateTimeProvider;
    _textData = GetTextDate();
}

With this change, we can alter the code of GetTextDate to use the provider:

private string GetTextDate()
{
    return string.Format("The current date is {0:d} ({0:dddd})", 
      _dateTimeProvider.Now);
}

Our tests need to be changed to pass the provider to the constructor of MainViewModel. We need to create a class that implements the interface and does what we want regarding to the date. In MainViewModelTests create the class FakeDateTimeProvider:

public class FakeDateTimeProvider : IDateTimeProvider
{
    private readonly DateTime _currentDateTime;

    public FakeDateTimeProvider(DateTime currentDateTime)
    {
        _currentDateTime = currentDateTime;
    }

    public DateTime Now
    {
        get { return _currentDateTime; }
    }
}

This class receives in the constructor the date we want as the current date. Now we can change our tests, passing an instance of this class:

[TestMethod]
public void CreateMainViewModel_TextDataShouldHaveText()
{
    IDateTimeProvider provider = new FakeDateTimeProvider(
       new DateTime(2013,1,1));
    var viewModel = new MainViewModel(provider);
    Assert.AreEqual("The current date is 01/01/2013 (Tuesday)", 
       viewModel.TextData);
}

[TestMethod]
public void CreateMainViewModel_Date01022013_TextDataShouldHaveText()
{
    IDateTimeProvider provider = new FakeDateTimeProvider(
       new DateTime(2013, 1, 2));
    var viewModel = new MainViewModel(provider);
    Assert.AreEqual("The current date is 01/02/2013 (Wednesday)",
       viewModel.TextData);
}

Our tests pass with no problems and we have removed the dependency to DateTime. The next step is to bind the ViewModel to the View. This is done setting the DataContext property of the view to an instance of the viewmodel. One way to do that is to put the following code on the constructor of the view:

public MainWindow()
{
    InitializeComponent();
    IDateTimeProvider provider = new SystemDateTimeProvider();
    DataContext = new MainViewModel(provider);
}

This works fine, but it has two problems:

  • We have to create an instance of SystemDateTimeProvider to pass it to the constructor of the viewmodel.
  • The viewmodel doesn’t work at design time, thus making it difficult to design the UI.

To overcome these two problems, we will use the ViewModelLocator technique, a class that will use Dependency Injection to locate and instantiate our viewmodels. We will use a Dependency injection framework to do it. There are many good ones in the market, most of them free: Castle Windsor, Autofac, StructureMap and Ninject are very good, but we will use Unity, a framework created by Microsoft Patterns and Practices.

We can install it using Nuget. On the solution Explorer, right-click the References node and choose “Manage Nuget Packages”. Search for Unity and install it:

Unity works in the following way: we register the interfaces with the associated concrete classes in the container and then we call the Resolve method to return the classes instances – all dependencies are resolved and the class instance is returned. There is no need to register the concrete classes if Unity can create them (by having a default parameterless constructor or with dependencies that can be resolved).

For example, the register phase in our classes would be:

_container = new UnityContainer();
_container.RegisterType<IDateTimeProvider, SystemDateTimeProvider>();

To get an instance of MainViewModel, we use something like:

_container.Resolve<MainViewModel>();

We do not need to register the MainViewModel class, because Unity can resolve all dependencies with the registered interfaces. Now, we can create a new class on the folder ViewModel, named ViewModelLocator:

private readonly UnityContainer _container;

public ViewModelLocator()
{
    _container = new UnityContainer();
    _container.RegisterType<IDateTimeProvider, SystemDateTimeProvider>();
}

public MainViewModel Main
{
    get { return _container.Resolve<MainViewModel>(); }
}

We register the IDateTimeProvider interface, associating it to the SystemDateTimeProvider class and create a property named Main that returns an instance of MainViewModel. To use this class, we add an instance to the Resources section of App.xaml. In App.xaml, add this code:

<Application.Resources>
     <viewModel:ViewModelLocator x:Key="Locator"/>
</Application.Resources>

Add the namespace for the ViewModelLocator in the Application class declaration:

<Application 
    x:Class="FakesTest.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewModel="clr-namespace:FakesTest.ViewModel"
    StartupUri="MainWindow.xaml">

Finally, in MainWindow, set the property DataContext to the property Main of the ViewModelLocator and bind the property Text of the TextBlock to the property TextData of the ViewModel:

<Window x:Class="FakesTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
    <Grid>
        <TextBlock x:Name="TxtDate" Text="{Binding TextData}"/>
    </Grid>
</Window>

When we do that, the current date data appears at design time:

We can then remove the code behind and our code in MainWindow.xaml.cs stays like that:

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Execute the program and observe that it behaves exactly in the same way as it did before. When we execute our tests, we see that they pass, but the first test (the one we’ve created in the prior article) doesn’t pass:

Test method FakesTest.Tests.MainWindowTests.CreateWindow_TextBlockHasCurrentDate threw exception: 
System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '5' and line position '9'. ---> System.Exception: Cannot find resource named 'Locator'. Resource names are case sensitive.

This is due to the fact that we have the dependency between the View and the ViewModelLocator. As we wanted to remove the dependency of Fakes, we can ignore this test, adding the Ignore attribute (we could remove this test, as it doesn’t make sense anymore, but I decided to leave it, as a reminder of the old times that should never come back J):

[Ignore]
[TestMethod]
public void CreateWindow_TextBlockHasCurrentDate()
{
    using (ShimsContext.Create())
    {
        ShimDateTime.NowGet = () => new DateTime(2013,1,1);
        var window = new MainWindow();
        var mainGrid = (Grid)window.Content;
        var textBlock = (TextBlock) mainGrid.Children[0];
        Assert.AreEqual("The current date is 01/01/2013 (Tuesday)",
           textBlock.Text);
    }
}

Conclusions

We finished our restructuring. Our code, once dependent of the Window and to DateTime, making it almost impossible to test, is now detached and 100% testable.

For that, we restructured the code using a ViewModel and Dependency Injection that resolves our dependencies in an automatic way, giving us a bonus of having the data at design time. We don’t need to use Fakes anymore and the program is ready for new updates.

 

Introduction

Sometimes you must do some changes on legacy programs that were not built using good development practices. At that time, our first reaction is to run away from that: the probability of having problems is too high and touching the source code is almost impossible – we are working on a castle of cards, where even the slightest move can bring everything down.

The idea of refactoring (or even rewrite) the code comes from a long time, but where is the time to do that? All projects are late and that’s not a priority, its working, no? Why touch on that?

We can make the situation a little better by creating unit tests for the changes we must do, but how to do that? The program is full of dependencies, the business rules are mixed with the views, and the methods are long and complicated.

The best we could do are integration tests, that are difficult to implement and slow to execute, they will be abandoned very soon. What to do now? The solution is at hand, Microsoft implemented a Microsoft Research’s project, named Moles, and put it in Visual Studio 2012 with the name of Fakes, so we can create test for anything, including .Net Framework classes.

With Fakes we can create unit tests that run fast and don’t depend of anything, nor operating system, machine or database. Here I must do a note: although Fakes can test almost anything, that’s not an excuse to relax our coding style – you must use good programming practices on the new code and do not rely on Fakes to simulate dependencies that should not exist. When you are creating new code, try to do it in a way that you don’t need Fakes, use it only where that is really needed.

The problem

To show how to use Fakes, we will create a small WPF project that has a window with a TextBlock:

 <Window x:Class="FakesTest.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     Title="MainWindow" Height="350" Width="525">  
   <Grid>  
     <TextBlock x:Name="TxtDate"/>  
   </Grid>  
 </Window>  

When the window is initialized, the TextBlock is fed with the current date:

 public partial class MainWindow  
 {  
   public MainWindow()  
   {  
     InitializeComponent();  
     TxtDate.Text = string.Format(  
      "The current date is {0:d}", DateTime.Now);  
   }  
 }  

We should change this code to put the weekday in the TextBlock, like in “The current date is 8/2/2013 (Friday)”. We want to use best practices and will create unit tests for the project. But how to do it? The code is mixed with the View and has a dependency on DateTime, a .Net Framework class.

Creating the test project

The first step is to create the test project. On the Solution Explorer, select the solution and right click it, selecting Add/New Project. Select Test/Unit Test Project and call it FakesTest.Tests. Add to it a reference to our project. Rename the UnitTest1.cs class to MainWindowTests.cs.

Here starts our problem: we want to test what is being shown in the TextBlock. For that, we must create a window, initialize it and look at its content. Not an easy task to do with unit tests.

 Here comes Fakes to rescue. On the test project, on the references, select the reference to the main project and select Add Fakes Assembly. A new reference to FakesTest.Fakes is added – this reference will create all fakes for the window and its componentes. To use it on our tests, we must add the references to System.Xaml, PresentationCore, PresentationFramework and WindowsBase.

 The next step is to create a fake for the DateTime class. Select the System assembly in the references and right click it, selecting Add Fakes Assembly. Now that we have all our environment “virtualized”, we can start creating tests.

To use the components created by Fakes we must surround the calls in a context, with the keyword Using, using a ShimsContext:

 using (ShimsContext.Create())  
 {  
   ….  
 }  

Inside the context, we must tell the behavior of the fake DateTime class, when the method Now will be called:

 ShimDateTime.NowGet = () => new DateTime(2013,1,1);  

To access the DateTime class created by Fakes, we must use the ShimDateTime class. The line above tells us that when the getter of the Now property is called (NowGet), it must return 1/1/2013. From now on, the test becomes exactly the same as any other unit test:

 [TestMethod]  
 public void CreateWindow_TextBlockHasCurrentDate()  
 {  
   using (ShimsContext.Create())  
   {  
     ShimDateTime.NowGet = () => new DateTime(2013,1,1);  
     var window = new MainWindow();  
     var mainGrid = (Grid)window.Content;  
     var textBlock = (TextBlock) mainGrid.Children[0];  
     Assert.AreEqual("The current date is 01/01/2013",textBlock.Text);  
   }  
 }  

We have created the window and verified if the TextBlock has the date we have passed on the fake. When we execute the tests with Ctrl+R+T, we see that the test passes. We are covered here, and we can make the changes we need on our code.

Changing the program

As we already have the test, we can change it for the new feature we want:

 [TestMethod]  
 public void CreateWindow_TextBlockHasCurrentDate()  
 {  
   using (ShimsContext.Create())  
   {  
     ShimDateTime.NowGet = () => new DateTime(2013,1,1);  
     var window = new MainWindow();  
     var mainGrid = (Grid)window.Content;  
     var textBlock = (TextBlock) mainGrid.Children[0];  
     Assert.AreEqual(  
      "The current date is 01/01/2013 (Tuesday)",textBlock.Text);  
   }  
 }  

We have made the change on the test but not on the code. If we run our test now, it will fail:

 Assert.AreEqual failed. Expected:<The current date is 01/01/2013 (Tuesday)>. Actual:< The current date is 01/01/2013>.  

We must change the code:

 public MainWindow()  
 {  
   InitializeComponent();  
   TxtDate.Text = string.Format(  
    "The current date is {0:d} ({0:dddd})", DateTime.Now);  
 }  

When we execute the test, it passes – our change is complete and working. To complete the Red-Green-Refactor cycle from TDD, we can refactor the code, extracting the function from where we set the TextBlock:

 public MainWindow()  
 {  
   InitializeComponent();  
   TxtDate.Text = GetTextDate();  
 }  
 private static string GetTextDate()  
 {  
   return string.Format(  
    "The current date is {0:d} ({0:dddd})", DateTime.Now);  
 }  

We run the tests and they still pass. The change is finished.

Conclusions

As we can see, Fakes helps a lot when we have legacy code that, for its dependencies, don’t allow creating unit tests in an easy way. What we have done here is to simulate the creation of a window and assign a value to a TextBlock, passing the current date with no special arrangement.

We are not advocating using this resource always – you should use Fakes only as the last resource, when the code is already there and there is not an easy way to break it. It can be used as a starting point for the real refactoring of the program: in this case, we must remove the window dependencies using the MVVM pattern and also from the System.DateTime, using some kind of wrapper interface (that we could call as IDateTimeProvider), but this is a subject for another article!

 

 

 

 

Ontem (9/2/2012) apresentei uma palestra na Campus Party 2012 e, ao final da palestra, mostrei uma série de recursos para aprendizado desta plataforma. Estou repetindo aqui, para que vocês possam verificar a quantidade disponível e aprender a desenvolver para Winddows Phone.

  • Windows SDK and Tools – http://create.msdn.com – Ponto de partida do AppHub, onde você pode baixar gratuitamente todas as ferramentas para desenvolver para Windows Phone
  • Windows Phone 7 Developer Portal – http://bit.ly/tIPZK3 – Portal de desenvolvimento do Windows Phone, com inúmeros recursos. Vale a pena começar com o Getting Started, onde há links para artigos, blogs e vídeos
  • Windows Phone 7 Training Kit – http://bit.ly/uKo8Fg – Link para download do training kit, contendo programas, exercícios para iniciar o aprendizado na prática
  • Livro Windows Phone 7 Development – Charles Petzold – http://charlespetzold.com/phone/index.html – Livro de 1000 páginas para download gratuito sobre desenvolvimento de Windows Phone
  • Videos Windows Phone 7 JumpStart – http://bit.ly/wp7jumpstart – Curso em vídeo com quase 20 horas sobre desenvolvimento para Windows Phone
  • Portal de Windows Phone da Microsoft em português – http://bit.ly/yxE8Po

Todos estes recursos são gratuitos, vocês não tem desculpas para não começar a aprender já!

On the last post, I’ve shown how we can animate transitions using Blend and Visual States. An important part in that mechanism is the use of behaviors. With behaviors, we can execute very complex actions, just by dragging a behavior into a window component. That’s very powerful and brings other benefits:

  • It’s reutilizable. We can include the same behavior in many different situations.
  • Allow that designers can include functionality in the design with no code.

We have two kinds of behaviors:

  • Actions – they execute an action associated to an event. For example, you can create an Action that, associated to a Textbox, “clicks” for every keystroke, or another action that makes the element below the mouse pointer grow.
  • Full behaviors – in this case, there is a more complex behavior, not necessarily associated to a trigger. One example is the MouseDragElementBehavior, that allows a dragging an element using the mouse.

Blend has predefined behaviors of the two kinds, with the end of the name telling its type (like in CallMethodAction or FluidMoveBehavior).

image_thumb

You can add new behaviors by searching the Blend gallery, at http://gallery.expression.microsoft.com (last time I’ve checked, there were 114 behaviors available there).

Behaviors are associated to an object and can have additional properties, beyond the trigger that activates them. For example, the GoToStateAction has the target component, the state to be activated and the boolean property UseTransitions as additional properties.

image

You can set the action’s properties and can also specify conditions for activate it. For example, when on the project from the previous post, we can use a checkbox to allow the transition activation. For that, we must click on the “+” button in front of Condition List, click on the advanced properties button from the condition and create a data binding with the checkbox’s property IsChecked. This way, the animation will only be triggered if the checkbox is checked.

image

If the predefined actions don’t do what we want, we can create custom actions to it. On the previous post, we use standard actions, but we had to create the Visual States. And we have another inconvenience: if we want to do animations that go up or down, we must create new Visual States. That way, we will create our action to do what we want, with no need of any special configuration.

On Visual Studio, create a new WPF project. We will add our Action to the project. Visual Studio, by default, doesn’t have the template to create actions. We could do that using Blend: after opening the project in Blend and selecting the Project panel, you can click it with the right button and select Add New Item and add an Action to the project.

image_thumb4 

Another way to do it is to use the Visual Studio online templates. On Visual Studio’s Solution Explorer, click with the right mouse button in the project and select Add New Item. Then go to Online Templates and fill the search box with action. Select the C# Action Template for WPF template and give it the TransitionControlAction name.

image_thumb7

The template adds a reference to System.Windows.Interactivity and creates a class similar to this code:

[sourcecode language='csharp'  padlinenumbers='true']
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace WpfApplication4
{
    //
    // If you want your Action to target elements other than its parent, extend your class
    // from TargetedTriggerAction instead of from TriggerAction
    //
    public class TransitionControlAction : TriggerAction<DependencyObject>
    {
        public TransitionControlAction()
        {
            // Insert code required on object creation below this point.
        }

        protected override void Invoke(object o)
        {
            // Insert code that defines what the Action will do when triggered/invoked.
        }
    }
}
[/sourcecode]

We have two action types: TriggerAction and TargetedTriggerAction. TriggerAction is an action that doesn’t act on another control. For example, if we want to create an action that starts Notepad when something happens, we would use a TriggerAction. TargetedTriggerAction makes reference to another element, called Target. This element is a property of the action and can be accessed in Blend.

We will create a TargetedTriggerAction. For that, we must change the class declaration to inherit from TargetedTriggerAction, like it’s shown in the comment in the beginning of the file. This action will execute the same code we’ve created on the first post to do the animation. We must also change the kind of object where it will be acting. We will use the FrameworkElement, because it has the properties ActualWidth and ActualHeight, which we will need.

[sourcecode language='csharp' ]
public class TransitionControlAction : TargetedTriggerAction<FrameworkElement>
[/sourcecode]

We will begin creating the enumeration for the animation kind and two DependencyProperties, the kind of animation we want and its duration. That way, these properties will be available in Blend.

[sourcecode language='csharp' ]
public enum AnimationKind
{
    Right,
    Left,
    Up,
    Down
}

[Category("Common Properties")]
public AnimationKind AnimationKind
{
    get { return (AnimationKind)GetValue(AnimationKindProperty); }
    set { SetValue(AnimationKindProperty, value); }
}

public static readonly DependencyProperty AnimationKindProperty =
    DependencyProperty.Register("AnimationKind", typeof(AnimationKind), typeof(TransitionControlAction));


[Category("Common Properties")]
public TimeSpan Duration
{
    get { return (TimeSpan)GetValue(DurationProperty); }
    set { SetValue(DurationProperty, value); }
}

public static readonly DependencyProperty DurationProperty =
    DependencyProperty.Register("Duration", typeof(TimeSpan), typeof(TransitionControlAction), 
    new UIPropertyMetadata(TimeSpan.FromMilliseconds(500)));
[/sourcecode]

We have added the Category attribute to the properties AnimationKind and Duration, so they can appear in the Common Properties group. When we compile the project and open it in Blend, we can see that our Action appears in the Assets panel.

image_thumb8

When we drag a TransitionControlAction to a button, its properties appear in the property editor:

image

Our action still doesn’t do anything. To do something, we must override the action’s Invoke method, adding the code that should be executed. We will use the code that we’ve created on the first post, modifying it to use the Target control:

[sourcecode language='csharp' ]
private void AnimateControl(FrameworkElement control, TimeSpan duration, AnimationKind kind)
{
    double xFinal = 0;
    double yFinal = 0;
    if (kind == AnimationKind.Left)
        xFinal = -control.ActualWidth;
    else if (kind == AnimationKind.Right)
        xFinal = control.ActualWidth;
    else if (kind == AnimationKind.Up)
        yFinal = -control.ActualHeight;
    else if (kind == AnimationKind.Down)
        yFinal = control.ActualHeight;
    var translate = new TranslateTransform(0, 0);
    control.RenderTransform = translate;
    if (kind == AnimationKind.Left || kind == AnimationKind.Right)
    {
        var da = new DoubleAnimation(0, xFinal, new Duration(duration));
        translate.BeginAnimation(TranslateTransform.XProperty, da);
    }
    else
    {
        var da = new DoubleAnimation(0, yFinal, new Duration(duration));
        translate.BeginAnimation(TranslateTransform.YProperty, da);
    }
}
[/sourcecode]

Finally, we must only call the method AnimateControl from the Invoke method:

[sourcecode language='csharp' ]
protected override void Invoke(object o)
{
    AnimateControl(Target, Duration, AnimationKind);
}
[/sourcecode]

With that, our behavior is finished. We can add the project in Blend, drag the action to the button, set the Target object to the grid and execute the project. When we click the button, the grid makes an animated transition on the selected direction. We don’t need to do anything else, the action is ready to be executed.

 

image

Conclusion

It’s been a long journey till here. We saw four different ways to animate the transition, we started from code and ended using the same code. On the middle of the way, we saw many new concepts: move from fixed code to a more flexible, refactored code, use components for transitions, eliminate code behind using the MVVM pattern, use NuGet, implicit templates, using Visual States to create animations with no code and, finally, behaviors to create actions that can be used by designers, in a flexible way, with no code. I hope you have enjoyed it!

On the two last posts, I’ve showed how to animate a transition using code. The first post showed how to animate the transition using code behind, creating the animation using code. The second post showed how to use components to ease these transitions. Although the use of components is a good alternative to create the animations using code, it still has some disadvantages:

  • You must add a reference to the component assembly or include its code in the project
  • It can have bugs – there may be many users of the components, but they still may have bugs. If they are open source with code available, you can still debug it, but is not always easy to debug such a component.
  • It can be outdated. With new versions of WPF and Silverlight, an old component may not work in the new versions.

So, we will see a new option to animate the transitions, with no code. You may be asking : “How is that, no code?”. Yes, WPF 4 (or 3.5, using the WPF Toolkit) and Silverlight have a resource that don’t need C# or VB code to animate transitions: Visual States. With Visual States, you define the state of your control in many situations and change between them with no need of code. Everything is done in XAML.

For this project, we won’t use Visual Studio. The creation of Visual States is easier in Blend. Open Blend and create a new WPF project.

In this project, add a row in the main grid, at the bottom of the window with 40 pixels of height. On this row, add a button with the property Content set to Hide. On the top row of the grid, add another grid, with red background. On the project panel choose the States tab. It should be empty.

image_thumb

Click on the first button on the top toolbar in the tab to add a new group state. Change its name to GridStates. Click on the second button of the GridStates toolbar to add a new state and change its name to Visible. Add another state and change its name to Hidden.

You should note that the default transition time (shown in front of the Default Transition text) is 0s.

image

Change this time to 1. Also change the Easing Function to CubicInOut, clicking the second button.

image

Looking at the image above, you can see we are in recording mode, recording the Hidden state. When we select a state in the states panel, all changes that we make in the layout are recorded for this state. So, we can change the appearance of our controls just by switching states. The state Visible is our default state. On the Hidden state we will hide our grid. The transition is done when we change from one state to another.

Select the grid and change the property RenderTransform X to –625, the property Opacity to 0 and the property Visibility to Collapsed. That way, the grid will move to the left, while it’s made transparent. Our states are ready. We could change between states using code behind, with this code on the button click event:

private void button_Click(object sender, System.Windows.RoutedEventArgs e) { VisualStateManager.GoToElementState(LayoutRoot, "Hidden", true); }

But that way, we would be on the same situation of the previous post, with code behind. Besides that, I have said that we would not use code!

Blend has a very interesting resource to execute actions with no code: Behaviors. Behaviors are custom actions that act on the components, with no need of code to execute them (in fact, someone needs to write code to create a behavior, but once it’s created, you just need to drag it to a component to use it). Blend comes with many predefined behaviors. To use them you should go to the Assets panel and select the Behaviors option.

image_thumb1[1]

We will use the GoToStateAction behavior. We drag this behavior to a component, then set the event that will trigger it and what is the new state that must be set when the event is triggered. Select the GoToStateAction and drag it to the button. A GoToStateAction is added to the button on the object inspector.

 

image_thumb2[1]

On the property editor we will configure the action.

image_thumb3

The trigger is already set: we want to activate the action when the button Click event is triggered. We must only set the state we want to select when the button is clicked. For that, we must set the StateName property to Hidden.

image

Our application is ready. When we execute it and click on the button, the transition occurs and moves the grid to outside. And all that with no lines of code!

We will make a small change to give more functionality to our application. Change the editor visualization to Split by clicking on the third button of view change.

image

With that, we can change the XAML code directly and change our button. We want it to be a ToggleButton. For that you must change the XAML component, changing its type from Button to ToggleButton:

<ToggleButton x:Name="button" Content="Hide" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="65" Height="25"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:GoToStateAction StateName="Hidden"/> </i:EventTrigger> </i:Interaction.Triggers> </ToggleButton>

The ToggleButton may be checked or not. We will show the Hidden state when it’s checked and the Visible state when it’s unchecked.

We must change the event that activates the Hidden state. On the object inspector, select the GoToStateAction and change the property  EventName to Checked. On the Assets tab, select another GoToStateAction and drag it to the button. Set the property EventName to  Unchecked and the property StateName to Visible. Run the program.

Now we have an animation to hide the grid when the button is checked and another to show the grid when the button is unchecked. Easy, no?

Here we could see the amount of resources we have available to create states and make them active. Everything is done visually, with no need of code. We still haven’t finished our journey, we still have other ways to animate transitions, but that is a subject for another post. See you there!

In the last post we saw how to animate a transition using code. As I said, I don’t think that is the best solution, because we must use code behind, something not easy to maintain. We could refactor code, creating a new class for the animation and use it. That would bring a little more separation, but we would have to still use code behind.

In this second part, we will use a different approach: third party components. We can use several components, like Kevin Bag-O-Tricks (https://github.com/thinkpixellab/bot), FluidKit (http://fluidkit.com), Silverlight Toolkit (http://silverlight.codeplex.com – only for Silverlight), or Transitionals (http://transitionals.codeplex.com).

We will use here Transitionals, for WPF. If we want to do animations for Silverlight, we should choose another component. Its use is very simple: after downloading the component and adding a reference in the project to the Transitionals.dll assembly, we must add a TransitionElement component in the place where we want the animation, configure the animation and add a content to the component. When the content is changed, the transition is activated.

Let’s create our transition project. Create a new WPF project and add a reference to Transitionals.dll. Then, add a TransitionElement to the main grid:

<Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="40" /> </Grid.RowDefinitions> <transc:TransitionElement x:Name="TransitionBox"> <transc:TransitionElement.Transition> <transt:TranslateTransition StartPoint="1,0" EndPoint="0,0" Duration="0:0:1"/> </transc:TransitionElement.Transition> </transc:TransitionElement> <Button Width="65" Grid.Row="1" Content="Hide" Margin="5" Click="Button_Click" /> </Grid>

We must declare the namespaces for the TransitionElement and for the TranslateTransition in the main window:

<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:transc="clr-namespace:Transitionals.Controls;assembly=Transitionals" xmlns:transt="clr-namespace:Transitionals.Transitions;assembly=Transitionals" Title="MainWindow" Height="350" Width="525">

The next step is to add content to the TransitionElement:

<transc:TransitionElement x:Name="TransitionBox"> <transc:TransitionElement.Transition> <transt:TranslateTransition StartPoint="1,0" EndPoint="0,0" Duration="0:0:1"/> </transc:TransitionElement.Transition> <Grid Background="Red" /> </transc:TransitionElement>

The button click event handler changes the content of the TransitionElement and activates the transition:

private void Button_Click(object sender, RoutedEventArgs e) { TransitionBox.Content = new Grid() {Background = Brushes.Blue}; }

That way, the code is simpler, we just need to change the content of the element. Besides that, the Transitionals component has a lot of transition types, and we can set them in many ways. For example, the TranslateTransition has the properties StartPoint and EndPoint, saying where the transition starts and ends. To do it from left to right, StartPoint should be –1,0 and EndPoint, 0,0. From top to bottom, StartPoint should be 0,-1 and EndPoint, 0, 0. We can even do a diagonal transition using 1,1 and 0,0.

Eliminating Code Behind

One thing that can be improved here is the elimination of code behind, using the MVVM pattern. We will use the MVVM Light framework, that you can get at http://galasoft.ch or by installing it directly using NuGet, an add-in to Visual Studio to ease download and installation of libraries and tools in Visual Studio. If you still don’t have NuGet, go to http://nuget.org and download it.

Once you have installled NuGet, you can click with the right button in References in the Solution Explorer and select “Manage Nuget Packages”. Fill the search box with “mvvm” and install the MVVM Light package:

image_thumb2

This installs MVVM Light, adds the required references and creates a folder named ViewModel, with two files, MainViewModel.cs and ViewModelLocator.cs. MainViewModel.cs is the ViewModel related to the main window and ViewModelLocator is a ViewModel locator.

In MainViewModel.cs you should add a property of type ViewModelBase, which will contain the ViewModel related to the View of the component content:

private ViewModelBase content; public ViewModelBase Content { get { return content; } set { conteudo = value; RaisePropertyChanged("Content"); } }

Next, we will create two ViewModels, related to our views. The two ViewModels are very similar and have only one property:

public class ViewModelA : ViewModelBase { private string text; public string Text { get { return text; } set { text = value; RaisePropertyChanged("Text"); } } } public class ViewModelB : ViewModelBase { private string text; public string Text { get { return text; } set { text = value; RaisePropertyChanged("Text"); } } }

Then create in the Solution Explorer a folder named View and put there two UserControls, each one with a Grid and a TextBlock:

<UserControl x:Class="WpfApplication2.View.ViewA" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid Background="Red"> <TextBlock Text="{Binding Text}" FontSize="36" /> </Grid> </UserControl>

To eliminate code behind, we must bind the property Content of the TransitionElement with the property Content of the ViewModel:

<transc:TransitionElement x:Name="TransitionBox" Content="{Binding Content}"> <transc:TransitionElement.Transition> <transt:TranslateTransition StartPoint="1,0" EndPoint="0,0" Duration="0:0:1"/> </transc:TransitionElement.Transition> </transc:TransitionElement>

and eliminate the button click, replacing it with a Command:

<Button Width="65" Grid.Row="1" Content="Esconde" Margin="5" Command="{Binding HideCommand}" />

The HideCommand property is defined in MainViewModel:

private ICommand hideCommand; public ICommand HideCommand { get { return hideCommand ?? (hideCommand = new RelayCommand(ChangeContent)); } } private void ChangeContent() { Content = content is ViewModelA ? (ViewModelBase)new ViewModelB() {Text = "ViewModel B"} : (ViewModelBase)new ViewModelA() {Text = " ViewModel A"}; }

Finally we must set the DataContext for the main View:

<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:transc="clr-namespace:Transitionals.Controls;assembly=Transitionals" xmlns:transt="clr-namespace:Transitionals.Transitions;assembly=Transitionals" Title="MainWindow" Height="350" Width="525" DataContext="{Binding Source={StaticResource Locator}, Path=Main}">

When we execute the program we have something similar to this:

image_thumb4

The view isn’t shown, just the content’s class name. That is expected, as the property Content is of type ViewModelBase and its presentation is made by the method ToString(). We could have put the view as content, but this goes against the MVVM pattern: the ViewModel must not know about the View. A solution to show the View using the ViewModel as content is to use a resource available in WPF or in Silverlight 5: implicit Data Templates. In an implicit DataTemplate, we don’t set the Key property when declaring the Template, we only set its DataType. With that, WPF and Silverlight use this DataTemplate every time they must render some content of that type.

We declare the DataTemplates in the Windows’s resources section:

<Window.Resources> <DataTemplate DataType="{x:Type ViewModel:ViewModelA}" > <View:ViewA /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:ViewModelB}" > <View:ViewB /> </DataTemplate> </Window.Resources>

Now, when we execute the program, we have the transition between the two views, with no code behind.

 

image_thumb6

Conclusion

When we use components to animate transitions, we have the possiblity to create very complex transitions in an easy way, we only have to change the content of the control.

We also saw how to remove code from the code behind, adding it to a ViewModel, making it easier to maintain and allowing better testability. As a bonus, we saw how to use implicit DataTemplates and how to relate a View to a ViewModel with no need of code. This resource is only available on WPF and Silverlight 5.

Although you can think it doesn’t worth the effort (we eliminated just one line of code, trading it with two ViewModels, two Views and a new MVVM component), my intent here was to show you other resources, like using MVVM instead of code behind and how to use new features, like the implicit DataTemplate. In a larger application, that requires more work, these changes are justified.

These are not the only ways to do control transitions. On the next articles, we will see other ways. See you then!

Um dos benefícios indiretos de ser um MVP é que muitos produtores de ferramentas ou componentes cedem cópias de seus produtos para os MVPs para uso pessoal, para que possam usar, avaliar e, eventualmente, recomendar.

Eu uso muitas dessas ferramentas no meu dia a dia, e gosto muito delas. Assim, nada mais justo que fazer um post sobre elas e como elas ajudam meu dia-a-dia.

Sem dúvida, a ferramenta que eu mais uso é o ReSharper (http://www.jetbrains.com/resharper/), um add-in para o Visual Studio para aumentar sua produtividade. Ao usar o Visual Studio, ela está sempre lá, ativa, me ajudando a escrever o código.

Análise de código

Ao abrir um projeto, o ReSharper analisa seu código e começa a dar sugestões para melhorá-lo. Abrindo um projeto console, já vemos o seguinte no editor:

image

Do lado direito, é adicionada uma barra com as indicações de ajuda para seu código. O quadrado amarelo mostra que há avisos para melhoria de código. Se houver erros de compilação, o quadrado fica vermelho e, se seu código estiver ok, o quadrado fica verde. Abaixo do quadrado, estão linhas com os pontos onde há problemas. Se você passar o mouse sobre estas barras, uma tooltip irá mostrar o problema.

image

Para corrigir o erro, é muito fácil. É só clicar na barra e o editor é posicionado no local do erro. Uma lâmpada vermelha indica o erro e podemos clicar nela para ver as ações disponíveis. Esta lista pode ser selecionada com Alt-Enter. Aliás, se eu tivesse a possibilidade de escolher um único atalho de teclado para lembrar, seria este. Com o ReSharper e o Alt-Enter o seu código irá melhorar bastante!

 

image

Selecionamos a ação desejada e o ReSharper corrige o código (no caso, eliminando as cláusulas using desnecessárias). Para o erro seguinte, podemos ver que o parâmetro args de Main está ém cinza. Isto quer dizer que ele não está sendo usado na função. Quando colocamos o mouse em args aparece uma pirâmide, mostrando que há um refactoring a ser feito.

image

Aqui ele irá remover o parâmetro não usado. Além desta mudança, ele irá verificar todos os lugares onde a função é chamada e mudar a chamada a ela. Isto é ótimo quando colocamos um parâmetro e verificamos que ele não é mais necessário e queremos retirá-lo. Se fizermos isso, o código irá quebrar em todos os lugares onde a funçao é chamada. Com este refactoring, as chamadas são alteradas automaticamente. Fazendo esta mudança, nosso código fica ok, como mostra a figura abaixo.

image

O ReSharper está constantemente analisando nosso código e verifica a consistência na nomenclatura de variáveis e métodos. Você pode dizer como gosta de nomear os campos, propriedades e métodos e ele irá verificar a consistência para você.

image

Por exemplo, eu gosto de nomear meus campos privados usando CamelCase, iniciados com minúscula (sem um sublinhado antes). Assim, se eu colocar um campo com nomenclatura diferente, o ReSharper irá me avisar e se prontificar para alterar. Nada que um Alt-Enter não resolva. E ele irá mudar todas as referências para essa variável.

image

Melhoria do código

Além da consistência de nomes, ele ainda verifica a qualidade do seu código. Sim, eu sei que seu código (como o meu) é impecável, mas será que dá para melhorar? Veja na figura abaixo, uma aplicação WPF onde implementei o manipulador do evento Click do botão em codigo, com button1.Click += <tab><tab>.

image

O ReSharper mostra dois avisos e um lembrete. O primeiro aviso é sobre MainWindow. Ele indica que o tipo pai (Window) já foi declarado em outro lugar desta classe parcial e é desnecessário. Devemos lembrar que quando criamos uma janela WPF estamos criando uma classe parcial, declarada em dois lugares: no XAML e no arquivo de code behind. O XAML já declara que MainWindow é derivado de Window e podemos tirar esta declaração redundante do code behind. O segundo aviso é devido ao fato que podemos eliminar a criação do delegate ao adicionar o manipulador. O lembrete é para indicar que temos uma exceção de “não implementado”, indicação clara que devemos colocar código ali. Dois Alt-Enter e nosso código fica assim:

image

O ReSharper analisa seu código, verificando possíveis erros e melhorias. Ao digitar este código

image

Vemos na barra lateral um aviso e uma possível melhoria. O aviso indica que ToString é redundante e que devemos especificar uma cultura para a conversão. O fato de ser redundante faz com que ele possa ser eliminado. Alt-Enter e lá se vai ele. A melhoria está no for, indicando que pode ser convertido para uma expressão LINQ. Ao teclar Alt-Enter mais uma vez ficamos com o código assim:

image

Outras melhorias de código muito comuns são otimização de if e de return: quando colocamos um código como

 

if (x == 3) y = 2; else y = 5;

o ReSharper otimiza para:

y = x == 3 ? 2 : 5;

Ou então este código:

if (x == 3) return 2; else return 5;

 

Aqui teríamos duas otimizações: eliminar o else

if (x == 3) return 2; return 5;

ou então usar o operador ternário:

return x == 3 ? 2 : 5;

Refactoring

Mas isto não é tudo o que o ReSharper pode fazer por você. Seus recursos de refactoring e criação de código são fantásticos. Queremos extrair o código do manipulador de eventos para um novo método. Podemos teclar Ctrl-Shift-R (Refactor this) e o ReSharper irá mostrar os refactorings disponíveis.

image

Selecionamos o refactoring de extração de métodos e a seguinte tela é mostrada:

image

Podemos indicar os parâmetros, o nome da função e seu tipo de retorno. Ao clicar em Next, obtemos algo como

image

Criação de código

Podemos ainda inserir código a partir de templates. O ReSharper permite criar templates com código para novos arquivos ou snippets de texto.

image

 

Temos três tipos de templates:

  • Live templates – templates de snippets de código, inseridos como snippets normais do Visual Studio. Para acionar, teclamos o snippet e <tab> para inserir. Outra maneira de acionar estes templates é usando Ctrl-E-L. Na figura, criei o snippet propnp, que cria uma propriedade com backing field e chama o manipulador de PropertyChanged
  • Surround templates, que permitem envolver o código selecionado com um template, por exemplo, para envolver o código com try…catch. Eles são acionados com Ctrl-E-U.
  • File templates – que criam novos arquivos no nosso projeto, como classes, interfaces. Eles são acionados com Ctrl-Alt-Ins.

Vamos criar uma nova classe em nosso projeto. Teclamos Ctrl-Alt-Ins e criamos uma nova classe. Chamamos de NewClass. Teclamos Alt-Ins e inserimos o construtor para a classe. Nos parâmetros do construtor colocamos uma dependência:

image

Note que IDependency está em vermelho, pois não está definida. Teclamos Alt-Enter e as opções mostradas são as seguintes

image

Note que ele verificou que colocamos o nome do tipo iniciado com I, indicando uma interface e sugere a criação desta. Podemos então criar a interface a partir daqui. Após criar a interface, teclamos Alt-Enter novamente em IDependency e podemos declarar o campo para guardar a dependência:

image

A nossa interface foi criada no mesmo arquivo da classe. Podemos ir para sua declaração e teclar Alt-Enter. O ReSharper oferece para movê-la para um arquivo separado. É criado um arquivo IDependency.cs com a interface. Como vocês podem ver, é muito fácil criar e refatorar o código com o ReSharper. Ele facilita também a declaração de variáveis. Por exemplo, ao incluirmos o código

total = -1;

no construtor, vemos que total está em vermelho. Teclando Alt-Enter, temos as seguintes opções:

image

Podemos então criar um campo total no nosso código. Como vimos, temos diversas maneiras de mudar e melhorar nosso código.

Auxílio no XAML

Mas isso não é tudo. Podemos usar o ReSharper também no XAML, o que facilita bastante. Por exemplo, se criamos um Converter no código:

public class DebugConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } }

Quando queremos usá-lo no XAML devemos seguir uma série de passos: namespace, declaração nos recursos, etc. Para isso, temos algumas facilidades.

image

Teclamos Alt-Enter em DebugConverter e selecionamos Create resource in type element <Window>. Ele cria a seção Resources e cria o recurso. Colocamos o nome DebugConverter. Não colocamos o namespace. Aparece uma tooltip indicando o namespace

image

Teclamos Alt-Enter e o namespace é declarado e colocado no elemento. Se não gostarmos do nome do namespace, podemos renomeá-lo com Ctrl-R-R. Pronto, a declaração do converter, o namespace, tudo está pronto, como necessário. Se tivermos um DataContext associado ao componente e ele não tiver uma propriedade chamada Valor, podemos usar o ReSharper para criar esta propriedade na classe do DataContext.

image

Navegação no código

O ReSharper possui atalhos para navegação no código, que facilitam muito. Por exemplo, Ctrl-T navega para um tipo. Abre-se uma tela como a seguinte

image

Digitamos parte do nome e ele mostra os símbolos definidos que casam com a pesquisa. Da mesma maneira, podemos usar Shift-Alt-T para ir para um símbolo ou Ctrl-Shift-T para ir a um arquivo. A pesquisa é feita em todos os arquivos da solução. A navegação entre os membros de uma classe pode ser feita com Alt-`. Você pode ir ao membro anterior ou posterior com Alt-Up ou Alt-Down. Se você quiser, pode até navegar em código .NET descompilado. O ReSharper tem um descompilador que descompila o código e permite navegar até ele.

image

Utilidades diversas

Mas isto não é tudo o que o ReSharper oferece. Você tem um unit test runner, onde pode rodar os seus testes unitários. Você pode estar pensando quo o Visual Studio já tem um test runner, mas o que o VS oferece é exclusivo para testes com MSTest. O runner do ReSharper funciona com outros frameworks de teste, como o NUnit, QUnit ou xUnit. Uma outra funcionalidade interessante é o Explore Stack Trace. Você tem o stack trace de uma exceção, obtido através de uma ferramenta de log qualquer. Basta copiar o stack trace para a área de transferência e, no Visual Studio, usar Ctrl-E-T. O stack trace é mostrado com links para o seu código, e você pode assim verificar onde ocorreu a exceção.

image

Conclusão

Esta é só parte da funcionalidade oferecida pelo ReSharper, há muito mais para explorar, mas isto eu deixo para vocês. A ferramenta é paga, mas você pode baixar uma versão de avaliação por 30 dias, em http://www.jetbrains.com/resharper/download/index.html.

Em conclusão, eu acho que esta é uma ferramenta indispensável para quem desenvolve com o Visual Studio, e só tenho um ponto contrário: ela é realmente viciante, e uma vez que você se acostuma a usar o Resharper, é muito difícil voltar a desenvolver sem ele Alegre

No post anterior mostramos os behaviors em Blend e apresentamos os dois tipos de behaviors: Actions e Behaviors.

Ali, mostramos como criar uma Action, que atua sobre um elemento Target, fazendo uma ação sobre ele. Neste post, iremos mostrar os Behaviors e como podemos criar um behavior para ser usado (e reutilizado) no Blend.

Um behavior atua sobre um elemento associado e executa uma determinada ação, que não precisa ser sobre outro elemento, pode ser inclusive sobre ele mesmo. Aqui iremos mostrar como criar um behavior para movimentar elementos de uma listbox arrastando e soltando-os na nova posição.

Antes de iniciar o desenvolvimento do behavior, devemos saber como fazer o Drag & Drop em WPF. Para que um componente possa suportar Drag & Drop, devemos configurar sua propriedade AllowDrop para True. Em seguida, devemos manipular dois eventos: DragOver, que é ativado quando algo está sendo arrastado sobre o elemento e Drop, quando algo é solto sobre o elemento.

No evento DragOver devemos dizer qual é o cursor que deve ser apresentado quando há algo sendo arrastado sobre o elemento. Usamos o segundo parâmetro do manipulador de eventos, do tipo DragEventArgs, configurando a propriedade Effects com um código semelhante a este:

 

void ListboxDragOver(object sender, DragEventArgs e) { e.Effects = DragDropEffects.Move; }

Este código faz que o cursor de movimentação seja mostrado. No evento Drop devemos concluir a ação.

Com esta pequena introdução, podemos criar nosso behavior. Desta vez, iremos iniciar nosso projeto no Blend. Crie um novo projeto WPF, do tipo WPF Application

image

Em seguida, vá para o menu Project e selecione Add New Item, escolhendo a opção Behavior. Dê o nome de DragListItemBehavior

image

O Blend cria um código semelhante ao seguinte:

using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Interactivity; //using Microsoft.Expression.Interactivity.Core; namespace WpfApplication5 { public class DragListItemBehavior : Behavior<DependencyObject> { public DragListItemBehavior() { // Insert code required on object creation below this point. // // The line of code below sets up the relationship between the command and the function // to call. Uncomment the below line and add a reference to Microsoft.Expression.Interactions // if you choose to use the commented out version of MyFunction and MyCommand instead of // creating your own implementation. // // The documentation will provide you with an example of a simple command implementation // you can use instead of using ActionCommand and referencing the Interactions assembly. // //this.MyCommand = new ActionCommand(this.MyFunction); } protected override void OnAttached() { base.OnAttached(); // Insert code that you would want run when the Behavior is attached to an object. } protected override void OnDetaching() { base.OnDetaching(); // Insert code that you would want run when the Behavior is removed from an object. } /* public ICommand MyCommand { get; private set; } private void MyFunction() { // Insert code that defines what the behavior will do when invoked. } */ } }

 

Devemos sobrescrever dois métodos, OnAttached e OnDetaching. No método OnAttached iremos fazer o processo de inicialização do nosso behavior: conectar manipuladores, configurar propriedades, etc. No método OnDetaching fazemos a limpeza do processo.

Agora que já temos nosso projeto criado, podemos editar seu código no Visual Studio. No painel Projects, clique com o botão direito do mouse sobre a solução e selecione Edit in Visual Studio. O projeto é aberto no Visual Studio.

image

Abra o arquivo do behavior para editá-lo. Queremos que o behavior só atue sobre ListBoxes. Para isto iremos alterar seu tipo:

public class DragListItemBehavior : Behavior<ListBox>

Em seguida, devemos colocar, no método OnAttached, o código de inicialização, onde iremos configurar as propriedades e conectar os manipuladores:

protected override void OnAttached() { base.OnAttached(); AssociatedObject.AllowDrop = true; AssociatedObject.PreviewMouseLeftButtonDown += ListboxPreviewMouseLeftButtonDown; AssociatedObject.DragOver += ListboxDragOver; AssociatedObject.Drop += ListboxDrop; }

Note que conectamos os eventos DragOver e Drop, mas também usamos o evento PreviewMouseLeftButtonDown. Isto é necessário por que iremos iniciar a ação de Drag & Drop quando o usuário clica num item da Listbox. O behavior tem uma propriedade AssociatedObject, que é o objeto associado ao behavior. Como definimos que esse é um Behavior<ListBox>, o AssociatedObject é uma Listbox.

No método OnDetaching iremos fazer a limpeza:

protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewMouseLeftButtonDown -= ListboxPreviewMouseLeftButtonDown; AssociatedObject.DragOver -= ListboxDragOver; AssociatedObject.Drop -= ListboxDrop; }

Podemos então criar o código para fazer o Drag & Drop nos manipuladores dos eventos. No evento PreviewMouseLeftButtonDown obtemos o item que foi clicado e iniciamos o processo de Drag & Drop:

private object dragItem; private void ListboxPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var parent = (ListBox)sender; dragItem = GetDataFromListBox(parent, e.GetPosition(parent)); if (dragItem != null) DragDrop.DoDragDrop(parent, dragItem, DragDropEffects.Move); }

O método GetDataFromListBox procura na árvore de elementos e retorna o item que foi clicado:

private object GetDataFromListBox(ListBox source, Point point) { var element = source.InputHitTest(point) as UIElement; if (element == null) return null; object data = DependencyProperty.UnsetValue; while (data == DependencyProperty.UnsetValue) { data = source.ItemContainerGenerator.ItemFromContainer(element); if (data == DependencyProperty.UnsetValue) element = VisualTreeHelper.GetParent(element) as UIElement; if (element == source) return null; } return data != DependencyProperty.UnsetValue ? data : null; }

No evento DragOver iremos configurar o cursor. Se o Drag & Drop é da própria Listbox, deixamos arrastar, senão configuramos o cursor para None:

private void ListboxDragOver(object sender, DragEventArgs e) { e.Effects = e.Source == sender ? DragDropEffects.Move : DragDropEffects.None; }

Finalmente, no evento Drop fazemos a movimentação do item arrastado:

private void ListboxDrop(object sender, DragEventArgs e) { var parent = (ListBox)sender; var dropItem = GetDataFromListBox(parent, e.GetPosition(parent)); var dragItemIndex = parent.Items.IndexOf(dragItem); var dropItemIndex = dropItem == null ? parent.Items.Count - 1 : parent.Items.IndexOf(dropItem); if (dragItemIndex != dropItemIndex) { parent.Items.RemoveAt(dragItemIndex); parent.Items.Insert(dropItemIndex, dragItem); } }

Verificamos onde o item arrastado foi solto e, se for numa posição diferente da atual, movemos o item para uma nova posição. Nosso behavior está pronto. Compile o projeto e abra o Blend para recarregá-lo. Nosso behavior está lá e pode ser usado.

 

image

Coloque uma Listbox na janela e coloque alguns itens nela. Arraste um DragListItemBehavior para a Listbox. Execute o programa. Você pode ver que podemos arrastar os itens da Listbox para movê-los de lugar. Este behavior é reutilizável e pode ser usado em qualquer Listbox, mesmo por aqueles que não tem conhecimento de C#. Como você pode ver, um behavior pode modificar o comportamento de outros componentes, estendendo-os e trazendo novos comportamentos, sem que seja necessário criar um controle derivado.

No último post mostramos como animar transições usando o Blend e Visual States. Uma parte importante naquele mecanismo é o uso de behaviors. Com behaviors, podemos executar ações bastante complexas, apenas arrastando um behavior para um componente da janela. Isto, além de poderoso, traz outros benefícios:

  • É reutilizável. Podemos incluir o mesmo behavior em diversas situações
  • Permite que os designers possam incluir funcionalidade no design sem necessidade de código

Temos dois tipos de behaviors:

  • Actions – executam uma ação associado a um evento. Por exemplo, você pode criar uma Action que, associada a uma TextBox, emite um “click” a cada tecla pressionada, ou outra action que faz um controle crescer quando o mouse está sobre ele
  • Full behaviors – neste caso, há um comportamento mais complexo, não necessariamente associado a um único trigger. Um exemplo disso é o MouseDragElementBehavior, que permite movimentar um elemento, arrastando-o com o mouse

No Blend, encontramos os dois tipos de behaviors, com o final do nome indicando o tipo (ex. CallMethodAction ou FluidMoveBehavior).

image

Além dos pré-instalados, você pode encontrar outros behaviors, na galeria do Blend, em http://gallery.expression.microsoft.com (quando verifiquei, existiam 114 behaviors disponíveis lá).

Os behaviors estão associados a um objeto e podem ter propriedades adicionais, além do trigger que os ativa. Por exemplo, o GoToStateAction tem como propriedades adicionais o componente destino e o estado a ser ativado, além da propriedade booleana UseTransitions, para usar as transições para mudar de um estado a outro.

image

Além de configurar as propriedades da Action, você pode especificar condições para que ela possa ser ativada. Por exemplo, usando o projeto do post anterior, podemos usar uma checkbox para permitir a ativação da transição. Para isso, basta clicar no botão “+” de Condition List, clicar no botão de propriedades avançadas da condição, criar um Data Binding com a checkbox e fazer um binding com a propriedade IsChecked. Desta maneira, a animação só será ativada se a checkbox estiver checada.

image

Além das Actions padrão, podemos criar Actions personalizadas para fazer o que queremos. No post anterior, usamos as Actions padrão, mas precisamos criar os Visual States. Além disso, temos um outro inconveniente: se quisermos fazer as animações para cima ou para baixo, temos que criar novos Visual States. Assim, criaremos nossa Action para fazer o que queremos, sem a necessidade de configuração especial.

No Visual Studio, crie um novo projeto WPF. Vamos adicionar agora a nossa Action. O Visual Studio, por padrão, não tem o template para criar uma Action. Poderíamos fazer isso usando o Blend. Ao abrir o projeto no Blend e selecionar a aba Project, você pode dar um clique com o botão direito do mouse, selecionar Add New Item e adicionar uma Action ao projeto.

image 

Outra maneira de fazer isso é usar os templates online do Visual Studio. No Solution Explorer do Visual Studio, clique com o botão direito do mouse no projeto e selecione Add New Item. Na tela, vá para Online Templates e tecle action na caixa de pesquisa. Selecione o template C# Action Template for WPF e dê o nome de TransitionControlAction.

image

O template adiciona uma referência a System.Windows.Interactivity e gera uma classe semelhante a este código:

using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Interactivity; namespace WpfApplication4 { // // If you want your Action to target elements other than its parent, extend your class // from TargetedTriggerAction instead of from TriggerAction // public class TransitionControlAction : TriggerAction<DependencyObject> { public TransitionControlAction() { // Insert code required on object creation below this point. } protected override void Invoke(object o) { // Insert code that defines what the Action will do when triggered/invoked. } } }

Temos dois tipos de actions: TriggerAction e TargetedTriggerAction. TriggerAction é uma action que não se refere a outro controle. Por exemplo, se quisermos criar uma action que executa o Notepad quando acontece um evento, usaríamos uma TriggerAction. TargetedTriggerAction refere-se a um outro elemento, chamado de Target. Este elemento é uma propriedade da action e pode ser acessado no Blend.

Nós iremos criar uma TargetedTriggerAction. Portanto devemos mudar o código para derivar de TargetedTriggerAction, como mostra o comentário no início da classe. Esta action irá executar o mesmo código que criamos no primeiro post para fazer a animação. Devemos alterar também o tipo de objeto em que ela atua. Usaremos o FrameworkElement, pois este elemento tem as propriedades ActualWidth e ActualHeight.

public class TransitionControlAction : TargetedTriggerAction<FrameworkElement>

Inicialmente, iremos criar a enumeração para as posições e duas DependencyProperties com o tipo de animação desejada e a duração, de modo que ela possa ser selecionada no Blend.

public enum TipoAnimacao { Direita, Esquerda, Cima, Baixo } [Category("Common Properties")] public TipoAnimacao Tipo { get { return (TipoAnimacao)GetValue(TipoProperty); } set { SetValue(TipoProperty, value); } } public static readonly DependencyProperty TipoProperty = DependencyProperty.Register("Tipo", typeof(TipoAnimacao), typeof(TransitionControlAction)); [Category("Common Properties")] public TimeSpan Duracao { get { return (TimeSpan)GetValue(DuracaoProperty); } set { SetValue(DuracaoProperty, value); } } public static readonly DependencyProperty DuracaoProperty = DependencyProperty.Register("Duracao", typeof(TimeSpan), typeof(TransitionControlAction), new UIPropertyMetadata(TimeSpan.FromMilliseconds(500)));

Note que colocamos o atributo Category nas propriedades Tipo e Duração para que elas apareçam junto com o grupo Common Properties. Ao compilarmos o projeto e abri-lo no Blend, vemos que nossa action aparece na aba Assets.

image

Ao arrastarmos uma TransitionControlAction para um botão, as propriedades aparecem no editor de propriedades:

image

Mas nossa action ainda não faz nada. Para fazer algo, devemos sobrescrever o método Invoke da action, colocando ali o código que deve ser executado. Usaremos o código que escrevemos na primeira postagem, modificando um pouco para usar o controle Target:

private void AnimaControle(FrameworkElement controle, TimeSpan duração, TipoAnimacao tipo) { double xFinal = 0; double yFinal = 0; if (tipo == TipoAnimacao.Esquerda) xFinal = -controle.ActualWidth; else if (tipo == TipoAnimacao.Direita) xFinal = controle.ActualWidth; else if (tipo == TipoAnimacao.Cima) yFinal = -controle.ActualHeight; else if (tipo == TipoAnimacao.Baixo) yFinal = controle.ActualHeight; // cria a transformação e atribui ao controle var translate = new TranslateTransform(0, 0); controle.RenderTransform = translate; // cria a animação e anima-a if (tipo == TipoAnimacao.Esquerda || tipo == TipoAnimacao.Direita) { var da = new DoubleAnimation(0, xFinal, new Duration(duração)); translate.BeginAnimation(TranslateTransform.XProperty, da); } else { var da = new DoubleAnimation(0, yFinal, new Duration(duração)); translate.BeginAnimation(TranslateTransform.YProperty, da); } }

Finalmente, basta chamar o método AnimaControle a partir do método Invoke:

protected override void Invoke(object o) { AnimaControle(Target, Duracao, Tipo); }

Com isto, nosso behavior está completo. Podemos abrir o projeto no Blend, arrastar a action para o botão, configurar o objeto Target apontando para a grid e executar o projeto. Ao clicar o botão, a grid faz uma transição animada para a direção selecionada. Note que não precisamos fazer nada. Basta arrastar a action para o botão, configurar o elemento Target e as propriedades. A action está pronta para ser executada.

image

Conclusão

Foi um longo trajeto até aqui. Vimos quatro maneiras diferentes de animar a transição, começamos com código e terminamos usando o mesmo código. No meio do caminho vimos diversos conceitos: partir de um código fixo para um código mais refatorado e flexível, usar componentes para transição, eliminar o code behind usando MVVM, usando o Nuget, Templates Implícitos, usar Visual States para criar animações sem usar código e, finalmente, behaviors, para criar ações que podem ser usadas por designers, de maneira flexível e sem usar código. Espero que tenham gostado!