One of the indirect benefits of being a Microsoft MVP is that many tool or component producers give copies for MVPs for their personal use, so they can use, evaluate and, if they like it, recommend it.

I use many of these tools on a daily basis and like them very much. So nothing more fair than write a post about them and how they help my work.

There is no doubt that the tool I use the most is ReSharper (, an add-in for Visual Studio to enhance your productivity. When I use Visual Studio, it’s always there, helping me to write code.

Code analysis

When you open a project, ReSharper will analyze your code and start to give you suggestions to enhance it. When you open a console project, you will see something like this on the editor:


On the right side, a new bar is added with help indicators for your code. The yellow square at the top shows that there are warnings to improve your code. If it’s red, there are compile errors and, if your code is ok, the square turns green. Below the square, there are some bars indicating the points where problems are found. If you hover the mouse over the bars, a tooltip will show the problem.


Fixing the error is very simple. You just have to click on the bar and the editor will be positioned on the place of the error. A red bulb will indicate the error and we can click on it to show the available actions. This list can be selected with Alt-Enter. If I could only remember one ReSharper shortcut, this would be the one. It will do many fixes for you, with Alt-Enter your code will improve a lot!



We select the desired action and ReSharper corrects the code (by eliminating the using clauses not needed). To fix next error, we can see that the args parameter in the Main function is in gray. That means that it’s not being used there. When we put the mouse over the args parameter, ReSharper shows a pyramid, indicating that there is a refactoring to be made.



It will remove the unused parameter. Besides this change, it will verify all places where the function is called and change its call. That’s great when we add a parameter and later we verify it is not needed and we want to remove it. If we do that, all places where the function is called will not compile. With this refactoring, our code won’t break anymore.



ReSharper is constantly analyzing our code and checking consistency on variables and methods names. You can tell how do you like to name the fields, properties and methods and it will check the consistency for you.



For example, I like to name my private fields using CamelCase, starting with a lowercase character (with no leading underscore). If I put a field using a different naming, ReSharper will tell me and ask to change it. Just press Alt-Enter and it will change the name and all references to this variable.


Code improvement

ReSharper also verifies the quality of your code. Yes, I know that your code (like mine) is wonderful, but can it be improved? Take a look on the figure below, where I have a WPF application where I’ve added the event handler of the Click event for a button in code, using button1.Click += <tab><tab>.


ReSharper shows two warnings and a reminder. The first warning is about MainWindow. It shows that the parent type (Window) has been already declared and is not necessary. We should remember that when we create a WPF window we are creating a partial class, declared in two places: on the XAML and on the code behind. The XAML already tells that MainWindow inherits from Window and we can remove this redundant declaration from the code behind. The second warning is due to the fact that we can eliminate the delegate creation when adding the handler. The reminder is to tell us that we have a “Not Implemented” exception, a clear indication that we must add code there. Pressing Alt-Enter twice, and our code will be changed to:


ReSharper analyses your code, checking for improvements and possible errors. When you enter this code


you can see on the bar on the right a warning and a possible improvement. The warning tells us that ToString is redundant and that we must specify a culture for the conversion. The fact that it’s redundant makes it a candidate for elimination. Alt-Enter and there it goes. The next improvement is in the for, that can be converted to a LINQ expression. Pressing Alt-Enter again we end up with this code:


Other common code improvements are if and return optimizations: when we put something like this


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

ReSharper optimizes to:

y = x == 3 ? 2 : 5;

Or this code:

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

Here, we have two optimizations: eliminate the else

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

or use the ternary operator:

return x == 3 ? 2 : 5;


That’s not all that ReSharper can do for you. Its refactoring tools and code creation are fantastic. If we want to extract the code from the event handler to a new method, we can press Ctrl-Shift-R (Refactor this) and ReSharper will show all available refactorings.


We select the extract method refactoring and this screen is shown:


We can indicate the parameters, the function name and its return type. By clicking on Next, we get something like


Code creation

We can also insert code using templates. ReSharper allows to create templates with code for new files or code snippets.



We have three kinds of templates:

  • Live templates – code snippets templates, inserted like Visual Studio snippets. To insert them, we must add the snippet name and press <tab> to insert. One other way to insert these snippets is by using Ctrl-E-L. On the figure above, I’ve created the propnp snippet, that creates a property with a backing field and calls the PropertyChanged handler.
  • Surround templates, that surround the code with a template, like to surround the code with a try…catch. They can be invoked with Ctrl-E-U.
  • File templates – they create new files on our project, like new classes or interfaces. They are invoked with Ctrl-Alt-Ins.

We will create a new class in our project. We press Ctrl-Alt-Ins and create a new class, calling it NewClass. We then press Alt-Ins and insert the constructor for the class. On the constructor parameters, we insert a dependency:


Note that IDependency is in red, because we have not defined this interface. We press Alt-Enter and these options are shown:


ReSharper has noted that we’ve set the type name starting with ’I’ and suggests to create a new interface. We can create our interface from here. After creating the interface, we press Alt-Enter again in IDependency in the constructor and we can declare a field to store the dependency:


Our interface was created on the same file as the class file. We can go to its declaration and press Alt-Enter. ReSharper offers to move it to a different file. A new IDependency.cs file is created with the interface. Easy, no? It also eases the variables declaration. For example, when we enter code like

total = 1;

on the constructor, we see that total is in red. Pressing Alt-Enter we have these options:


We can create a total field on our code. As we can see, we have many ways to change and improve our code.

XAML help

But that is not alll that we get. We can use ReSharper also while editing XAML code. For example, if we create a Converter in code:

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; } }

When we want to use it in XAML, we must follow some steps: namespace, resource declaration, etc. ReSharper can help us for that.


We press Alt-Enter in DebugConverter and select Create resource in type element <Window>. ReSharepr creates the Resources section and creates the resource. We add the name DebugConverter with no namespace. A tooltip is shown indicating the needed namespace


We then press Alt-Enter and the namespace is added to the window declaration and the prefix added to the element. If we don’t like its name, we can rename it with Ctrl-R-R. Everything needed is ready, now. If we have a DataContext associated to the element and it doesn’t have a property named Valor, we can use ReSharper to create this property on the DataContext class, like a ViewModel.


Code navigation

ReSharper has many shortcuts for code navigation. For example, Ctrl-T navigates to a defined type. A screen like this open is opened


We enter part of the name and it shows all types that match with the search. On the same way, we can use Shift-Alt-T to go to a symbol or Ctrl-Shift-T to go to a file. The search is done in all solution’s files. The navigation between members of a class can be done with Alt-`. You can go to the previous or next member with Alt-Up or Alt-Down. If you want, you can even go to a decompiled .net code. ReSharper has a decompiler that decompiles the code and allows navigating to it.


Misc utilities

You have many othere goodies in ReSharper. You have a unit test runner, where you can run your unit tests. You may be thinking that Visual Studio already has a test runner, but the one VS has runs only MSTest tests. ReSharper runner works with MSTests, NUnit, QUnit or xUnit. One other interesting functionality is the Explore Stack Trace. You have an exception stack trace that comes from any source. You can copy the stack trace to the clipboard and, in Visual Studio, use Ctrl-E-T. The stack trace is shown with links to your code, so you can go to the place where the exception occurred.



This is just part of the functionality offered by ReSharper, there is much more to explore, but I leave that for you. This is a paid tool, but you can download a 30 days trial version in

I really think this is an indispensable tool for everyone who develops with Visual Studio, I just have a point against it: it is really addictive and once you get used to using ReSharper, it’s very difficult to develop without it. wlemoticon-smile

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 – – Ponto de partida do AppHub, onde você pode baixar gratuitamente todas as ferramentas para desenvolver para Windows Phone
  • Windows Phone 7 Developer Portal – – 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 – – Link para download do training kit, contendo programas, exercícios para iniciar o aprendizado na prática
  • Livro Windows Phone 7 Development – Charles Petzold – – Livro de 1000 páginas para download gratuito sobre desenvolvimento de Windows Phone
  • Videos Windows Phone 7 JumpStart – – Curso em vídeo com quase 20 horas sobre desenvolvimento para Windows Phone
  • Portal de Windows Phone da Microsoft em português –

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).


You can add new behaviors by searching the Blend gallery, at (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.


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.


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.


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.


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.

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>

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

[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)));

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.


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


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);
        var da = new DoubleAnimation(0, yFinal, new Duration(duration));
        translate.BeginAnimation(TranslateTransform.YProperty, da);

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);

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.




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.


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.


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


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.


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.



On the property editor we will configure the action.


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.


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.


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 (, FluidKit (, Silverlight Toolkit ( – only for Silverlight), or Transitionals (

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="" xmlns:x="" 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 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 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:


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="" xmlns:x="" xmlns:mc="" xmlns:d="" 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="" xmlns:x="" 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:


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.




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 (, 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:


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.


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!



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.


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.


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ê.


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.


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>.


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:


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


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:


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;


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.


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


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


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.



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:


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


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:


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:


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.


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


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.


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


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.


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.



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

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