Setting up icons for a Silverlight OOB application

In Silverlight 3 and 4, it is possible to create a Silverlight application and to have the user install it on the desktop (aka Out Of the Browser OOB). This is a great way to offer a “light desktop” experience, where the application can be started from a shortcut on the desktop or the Start menu, but running on Silverlight so that you don’t need the full .NET framework, and can run it on PC and Mac as you like. You can even use the application when the PC is offline, which is not possible with an in-browser application. I am very excited about this feature, because I was one of the first to talk about how great such a feature would be to add a piece to the .NET continuum of client applications.

This post will show you how to create a new Silverlight application and enable it to run out of the browser. I decided to write it because of a small issue I had when trying to setup icons for an OOB application I was working on. The icons did not show up, and it was not quite clear why not: No error messages or warnings, it simply didn’t work. Finally, talking to my boss Nate Dunlap made me realize that for some reason the build action for the icons was set to Resource. Changing it to Content instead solved the issue.

To brand your application and make it easily recognizable, you should set icons for it. The icons are used in various locations for the OOB application: On the desktop in the shortcut; in the Start menu; in the taskbar. Getting the icons to show is actually quite easy, if you are careful about some details. Follow the steps:

  • Create a Silverlight application in Visual Studio 2010.
  • Add 4 icons for your application to the project, for example in a folder named “Resources”. You need to add all 4 icons, in PNG format, with sizes 16x16px, 32x32px, 64x64px and 128x128px.
  • Select each icon that you just added, and press F4. This opens the properties panel for the files. Make sure that the Build Action is set as Content, or else the icons will not show!
  • Open the project properties by right clicking on the project in Visual Studio Solution Explorer, and selecting Properties.
  • Select the tab Silverlight.
  • Check the checkbox marked “Enable running application out of the browser”.
  • Click the button marked “Out-of-browser settings”.

 

  • Select each icon corresponding to the desired size.

Fli6E5

 

  • Open the file MainPage.xaml and enter the code shown below. This adds a Button and a TextBlock to the scene.
<StackPanel x:Name="LayoutRoot"
            Background="White">
    <TextBlock x:Name="IntroTextBlock"
               FontSize="24"
               FontWeight="Bold"
               HorizontalAlignment="Center"
               Margin="10" />
    
    <Button Content="Install"
            x:Name="InstallButton"
            Margin="10"
            Width="100"
            Height="50"
            Click="InstallButton_Click" />
</StackPanel>

 

  • Open MainPage.xaml.cs and type the code below.
    • In the constructor, we check if the application is running inside or outside of the browser. Depending on that, we hide the Button by setting its Visibility to Collapsed, and change the text of the TextBlock.
    • If the Button is visible and gets clicked, the corresponding event handler is called. Installing the application requires just one line of code.
public MainPage()
{
    InitializeComponent();

    if (Application.Current.IsRunningOutOfBrowser)
    {
        InstallButton.Visibility
            = System.Windows.Visibility.Collapsed;
        IntroTextBlock.Text = "Check my icons!";
    }
    else
    {
        IntroTextBlock.Text = "Install me first!";
    }
}

private void InstallButton_Click(
    object sender, RoutedEventArgs e)
{
    Application.Current.Install();
}

 

  • Run the application once. You need to install the OOB application before you can debug it in Visual Studio. After starting the app, you should see the following scene:

 

  • Click on the Install button. This displays a confirmation dialog. Note the presence of the 128x128 icon that we defined in the Properties before.

 

  • After pressing OK, the application starts in OOB mode. Notice the small 16x16 icon in the window’s title bar. Also, you should see an icon in the application’s button in the task bar on Windows.

 

  • Close the application and return to the Project Properties page in Visual Studio.
  • Select the Debug tab and set the Start Action to “Installed out-of-the-browser application”. Make sure that you select the correct one.

From now on, when you start the app from Visual Studio (with F5 or Ctrl-F5), the OOB application will start immediately and you don’t need to uninstall and reinstall it.

Conclusion

Creating Out of the Browser applications is really easy in Visual Studio 2010 thanks to the corresponding dialogs. It is also easy to define icons for your application, which helps creating a stronger identity for your software. However, when you do so, make sure that the icons’ build action is set to Content!!

 

Quick tip: Commenting out properties in XAML

Often when you write XAML, you wish you could ignore a property temporarily. In code, it is easy to do: Just comment out the line where the property is set, and you are good to compile.

LayoutRoot.Background = new SolidColorBrush(Colors.Red);
//LayoutRoot.DummyProperty = "Ignored";
/* LayoutRoot.Another = "Ignored too"; */

In XAML it is not so easy, because XML (of which XAML is a dialect) does not have line comments, but only block comments. You can comment out a whole XAML element, but not just one property.

<!--<ThisBlockIsIgnored Hello="World"
                    Again="Blah">
    <Label Content="No parse" />
</ThisBlockIsIgnored>-->
<TextBlock Text="This is parsed"
   Tag="This too"
   <!--DummyAttribute="No parse"-->
   Margin="10"/>
This last blocks creates an error.

Commenting single properties in XAML requires just a little more initial work, but then it is very easy:

  • In the root tag, add a new xmlns statement to import the Open XML markup compatibility elements:
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  • Then, add another xmlns statement mapping a prefix of your choice (I like to use “ignore”) to an URI of your choice (for example “http://www.galasoft.ch/ignore”). Note that this URI does not need to point to anything on the web. This is just a unique resource identifier, something like a unique ID.
xmlns:ignore="http://www.galasoft.ch/ignore"
  • Finally, use the mc:Ignorable property to set the new prefix as ignorable.
mc:Ignorable="ignore"
  • Note: If you already had one ignorable prefix defined (for example the “d” prefix that Expression Blend and the Visual Studio designer use), no problems. Just add the new prefix to the Ignorable list with a space to separate the prefixes.
mc:Ignorable="d ignore"

The XAML parser honors the Ignorable property and will simply ignore any value prefixed by one of the prefixes defined in the list. Do not however use the Blend “d” ignorable prefix, because this has a special meaning for Blend and Visual Studio designer. The way described here defines a brand new prefix without any additional meaning. The “ignore” prefix can be used for properties or for whole blocks (including their content):

Single property:

<TextBlock Text="This is parsed"
   Tag="This too"
   ignore:DummyAttribute="No parse"
   Margin="10"/>

Whole block:

<ignore:ThisBlockIsIgnored Hello="World"
                    Again="Blah">
    <Label Content="No parse" />
</ignore:ThisBlockIsIgnored>  

The MVVM landscape at MIX10

The MIX conference this year had an open call for sessions, and 12 sessions were voted by the public out of 169. Surprisingly (or maybe not that surprisingly in fact), 3 sessions out of the 12 have the MVVM pattern in their title. This shows a lot of interest for this pattern which is helping the developer to create decoupled, testable, blendable applications in Silverlight and in WPF.

Since my session is one of the three, I decided to contact the other two speakers (we happen to run in the same circles ;)) and try to coordinate the content. I think that by talking to each other, we can organize our content so that we avoid overlap and offer a wider landscape to the audience.

The two other authors responded positively to my request, and this is roughly how it will look like. Of course some overlap is unavoidable, to set the context right and avoid misunderstandings. After all, MVVM is a pattern, and as such there are multiple possible implementations or even interpretations of the pattern. But I think that this way, you will get a wider, deeper overview of what MVVM has to offer for you today.

Rob Eisenberg’s “Build Your Own MVVM Framework”

Rob is coordinator on the Caliburn project (a very powerful MVVM framework), but this is not a Caliburn talk. Instead, Rob will take some of the features of this framework and demonstrate how to build them from scratch. This should be a must see for the people who want to understand what is involved in a MVVM application, and how to avoid taking a dependency on an external framework. Rob will also talk about additional topics not directly related to MVVM.

Shawn Wildermuth’s “RIA Services and MVVM: It Can Happen!”

Shawn is going to set the focus on MVVM applied to RIA Services applications. He will show you all the code, and then how external frameworks can help you in your task.

Laurent Bugnion’s “Understanding the Model-View-ViewModel Pattern”

In this talk, I will set primary focus on the Blendability, i.e. how to structure your application so that it works great in Expression Blend. For instance, how can you display “design time data” in Expression Blend, so that the designers have something to design against. I will also show some components included in my MVVM Light Toolkit and explain how they can help you solve some issues in your applications. My talk will apply to Windows Presentation Foundation as well as Silverlight.

To be noted

It is nice to note that Rob, Shawn and I are not employed by Microsoft, but “just” enthusiast users of the technologies we will talk about. There is a great community around Silverlight and WPF, and it is interesting to note that most of the MVVM frameworks (at the exception of PRISM which is not directly an MVVM framework) originate from outside of Microsoft. Let’s spread the word: MVVM is the pattern of choice when you work in WPF or Silverlight. Come visit our sessions, your life as a developer will be changed!

 

Avoiding issues when typing text in Bindings

The Binding class has a few properties that can be set to a text, including spaces. The properties StringFormat, TargetNullValue and FallbackValue are such properties. These properties exist in WPF and newly also in Silverlight 4.

For example, you can type:

Since these strings are typed within the Binding markup extension in XAML, they do not take quote signs, which leads the XAML editor to be a little confused, as the color coding shows: The text after the “This” turns to red in the figure above.

Color alone is not really an issue, but another factor makes these strings very difficult to enter by default: The editor is configured to enter a comma after each Property/Value pair in the Binding expression. If you open the XAML editor and start typing such a binding expression, you will end up with:

Of course this will crash and burn. However you can correct this: In Visual Studio 2010, select the menu Options / Text Editor / XAML / Miscellaneous and uncheck the option “Commas to separate MarkupExtension parameters”.

From now on, commas will not be added automatically, and you will feel free!

 

Talking in Las Vegas: MIX2010 and MVVM

Update: The session is officially on. See the MIX10 website.

MIX10: Speaker

This morning, very early (or very late depending how you see it), I learned that one of the sessions I submitted to the MIX 2010 open call for speakers had been picked by the public. Out of 169 sessions, only 12 were picked, so you imagine my feelings right now. Honestly, I am sure that this will be a good session, but it could have gone either way, and I had prepared myself mentally for the alternative possibility too.

Understanding the Model-View-ViewModel pattern

The Model-View-ViewModel pattern (also called MVVM) is a hot topic in today’s Silverlight and WPF world. This pattern facilitates modern development techniques such as separation of concerns (decoupling), unit testing and test driven development, work with modern tools such as Visual Studio 2010, Expression Blend and more.

In this session, Laurent (a user and promoter of MVVM since 2006) will introduce this pattern to you with many demos. We will talk about the basic components of a modern Silverlight or WPF application, and of additional helpers that will make your life as a developer much easier.

MVVM at MIX

Interestingly, 3 of the 12 open call sessions picked by the audience have “MVVM” in the title. Rob Eisenberg’s “Build Your Own MVVM Framework” and Shawn Wildermuth’s “RIA Services and MVVM: It Can Happen!”, in addition to mine, should cover the topic in depth. After thinking about it, I decided I will contact Rob and Shawn to talk to them about their session, and try to avoid overlap.

On my end, I will probably shift the focus a little more on what MVVM brings you from a designer (well, integrator)’s point of view, and how you can leverage this pattern to create beautiful applications. I will also, of course, talk about the MVVM Light Toolkit, the open source toolkit I have been developing since last year, and which encounters a great success.

Send me your suggestions

I would love to hear if you have topics you would like to hear about during the session. I have a pretty good idea of what I will talk about, but let me know what is really important for you. What aspects of MVVM do you want me to focus on? What components of MVVM Light? Let me know, and I will adapt the content to include these topics!

I am very much looking forward to this session, and will see you in March at MIX!

 

Quick tip: Finding Silverlight 4 documentation fast

The Silverlight 4 documentation is available online from Microsoft. However, it is not the fastest way to find documentation. Instead, you should know that the Silverlight 4 documentation is available online, it is just a little bit hidden.

“Also available for…”

When you navigate to an MSDN page, you will find a box letting you know that the page you are looking for is also available for Silverlight 3, .NET 3.0, .NET 3.5 or .NET 4. For example, here is what the page for System.Windows.Controls.Border shows:

No sign of Silverlight 4 yet. However, it is easy to get to the same page: In the URL of this page, replace the version number (VS.95) with (VS.96).

http://msdn.microsoft.com/en-us/library/system.windows.controls.border(VS.96).aspx

The version numbers are as follows:

  • (VS.85): .NET 3.0
  • (VS.90): .NET 3.5 SP1 (Note that you can also omit the version number altogether for this.
  • (VS.95): Silverlight 3
  • (VS.96): Silverlight 4
  • (VS.100): .NET 4

Of course some classes are not available for some versions, so you might get a Page Not Found.

Feeling lucky? Search from Bing or Google

In Google and in Bing, it is very fast to search for classes, methods or properties: Simply type the following query:

Border class

The first hit returned by the search engine is the MSDN Border class documentation. From there, you can use the navigation shown above. Another cool tip to go even faster: Type the same query followed by the version number. For example

Border class vs.96

Again, the first hit is what you are looking for.

Note: On Google, apparently you can even just type Border class 96 to get the result you want. On Bing, however, it returns other results first. Safer to type the vs. prefix first.

Since I set Bing to be my default search engine on Chrome and in IE8, I can type my queries directly in the browser’s location bar, and get the result page immediately.

MIX 2010: Voting for sessions has begun (I got two)

This year Microsoft decided to have an open call for sessions for the MIX 2010 in Las Vegas. This conference, in case you don’t know it yet, is a great 3 days about modern client technologies, such as ASP.NET, Windows Presentation Foundation and of course Silverlight. This year, MIX is taking place from the 15th to the 17th of March 2010 in the Mandalay Bay hotel in Vegas.

Today, the voting began! I didn’t count them, but there seems to be more than 100 sessions lined up, and the competition is fierce: Only 10 sessions will make the cut and be chosen for MIX. I just reviewed the speakers, and it is a pretty amazing line-up.

On my end, I submitted two sessions (see below). I honestly think that these two sessions will help the attendees become better developers in Silverlight and in WPF. The talks are based on years of experience with these two technologies, on real life projects.

A day in the life of a Silverlight/WPF Integrator

Vote here: http://visitmix.com/opencallvote/Entry?entryId=ADAYIN060

Abstract:

This session proposes an insight in the life of an integrator (sometimes called User Experience Developer or “Devigner”). How do we translate a creative designer’s vision into code, transforming it into interactive applications? What tools do we use, what tricks did we learn? This session will show you how to start from scratch and coordinate designers and developers to create a new rich application in Silverlight or Windows Presentation Foundation. We will see how to architect and structure the application according to the best practices in the field, and what workflows are involved. We will also see how to create and integrate XAML assets into the user interface. You will leave with a much better understanding on how the new integrator role is changing the way that client applications are developed.

You want to create beautiful applications? That’s what I do for a living, come and share the experience!

Having worked as an integrator for quite a few years now, in large distributed teams of developers and designers, I have identified many areas where the process is different from a classic application. The integrator role is a fairly recent role and many firms need guidance to understand how to start developing their Silverlight or WPF applications, and how to move from wireframes to design to development to testing.

We will also review the tools and the tips&tricks that make the life of an integrator easier. This is not just about Expression Blend, but about all the small helpers that facilitate the integration process.

Understanding the Model-View-ViewModel pattern

Vote here: http://visitmix.com/opencallvote/Entry?entryId=UNDERS103

Abstract:

The Model-View-ViewModel pattern (also called MVVM) is a hot topic in today’s Silverlight and WPF world. This pattern facilitates modern development techniques such as separation of concerns (decoupling), unit testing and test driven development, work with modern tools such as Visual Studio 2010, Expression Blend and more.

In this session, Laurent (a user and promoter of MVVM since 2006) will introduce this pattern to you with many demos. We will talk about the basic components of a modern Silverlight or WPF application, and of additional helpers that will make your life as a developer much easier.

From the maker of the MVVM Light Toolkit!

This talk is targeted at developers who keep hearing people talk about the Model-View-ViewModel pattern, but don’t quite know what it is, what it does, and how to get the best out of that. Again, few slides and a lot of code, as we will walk through the creation of a MVVM application and study the components that help separating the concerns in the application. We will also talk about external frameworks that help you creating new MVVM applications.

 

Believe it or not, it’s almost 2010

This year has been a pretty amazing year. A few weeks ago, I was writing about my first year at IdentityMine. A little more than one year ago I was closing the Siemens book (after around 13 years of working into Building Automation, but always from a software engineer perspective) and started the IdentityMine chapter of my life :). As I mention in the post in question, this first year was a very interesting and also challenging year. Interesting because I got to work with some of the best creative people and developers in the world. It’s always such a pleasure when I introduce myself to someone by saying I work at IdentityMine and to see a look of recognition on their face. This firm rocks, and I love being part of it. Challenging, because being the only European employee can be tough at times, even though the team has been amazing in making me a part of the family. To mitigate the distance, technical mediums like Twitter and Facebook, MSN and an IP phone have been super helpful. Of course nothing replaces the face-to-face contact, and my regular trips to Seattle (which will continue in 2010, I will be in Seattle again in February) make wonders to reconnect and continue the relationship. Surprisingly actually, the distance has not been as tough as I thought it might be. Of course it might not be OK for everyone to work this way, but it has been OK for me.

In the past year, I worked on multiple projects, in multiple roles

  • During presales, talking the the clients, identifying their needs, coming up with preliminary technical evaluations. Super interesting especially when you deal with the latest technology to do stuff that has never been done before.
  • Helping out for development tasks, working with a stellar team of developers and learning tons of new stuff in the process.
  • (my main role) Working as an integrator on various Silverlight and WPF projects. The integrator is the “missing link” between designers and developers. I take the inputs from designers and information architects (wireframes, comps) and extract the design assets to integrate them in the application. This is a great role, because you are the one who puts the final touch in the user experience, and it requires a very good knowledge of WPF, Silverlight and XAML, so it is yet another area where I have been learning tons of new things.
  • Consulting work, such as training clients’ teams, guiding them during the projects to make the best out of the technology, especially when designers are involved. This is a relatively new process, to have designers so involved into the application’s development, and I am lucky to have started working with designers very early on production projects. It is great to look back at this experience, analyze it, and then pass it back to clients and the community.
  • Talking at conferences, writing on my blog, interacting with the community and carrying proudly the name IdentityMine in front of people. I love to show what we do, and teach what I learned. I find that teaching and talking about technology is the best way to learn even more, and I love this. The highlight was of course talking at MIX09 (I had a session and took part to a half day workshop too), but all the other talks in various places in the US and in Europe were a fantastic time too.

Some of these tasks involved a lot of travelling, and it was a great year for my passport. Of all the trips, the ones I loved most were the long stay in Seattle in July, which was a great occasion to reconnect with many friends, make new ones, and then have my family join me for a vacation between Seattle, Victoria and Vancouver and then my visit to Macau and Hang Zhou in the summer, my first stay in both places, and I loved it. Of course the yearly pilgrimage to Las Vegas earlier in the year and the shorter trips to Belgium, Germany, Italy were all great times.

Private projects

I also had a few private projects going on in 2009, and had very exciting results. I published my MVVM Light Toolkit, a set of libraries and tools to make MVVM application development easier. It has encountered a great success so far, with hundreds of download (on Codeplex and on my website) and many, many interesting requests, discussions, etc. I am really excited about what is happening there, and will continue to work on it in 2010.

Of course my blog has been keeping me busy too, and I loved to wrote a few in-depth articles about Silverlight, WPF, MVVM and other topics. I saw a constant progression of subscribers this year, which is of course a great feeling, but also made me feel very humble and eager to produce quality articles.

The last big project is also one that is taking a lot of time, which is why the two other projects I mentioned here are maybe going to slow down a little in the beginning of 2010: I started working on Silverlight 4 Unleashed, the sequel to my first book Silverlight 2 Unleashed. This is a huge job, and I hesitated a lot before accepting to write it. I am now in the process of writing, and while it is really something I like to do, it is unavoidable that some things are going to suffer a little from this extra activity. So to the users of MVVM Light, and to readers of my blog, I ask you to be patient and don’t worry, normal activity will resume eventually ;)

And 2010?

2010 is going to be a great year too. My first big trip of the year is going to be to Seattle, again an occasion to meet friends from IdentityMine and from the community. Can’t wait for this trip. The next one should be to MIX10 in Vegas, and those who know me know how much I love this conference, and this year should be no exception. I am also scheduled to talk in a couple of conferences in Europe, more about this later on my blog.

It is a fantastic privilege to be involved in such a wonderful community. To all of you who make this possible, thank you thousand times. You did truly change my life. I cannot wait to see what the future has in store for us, and I am sure 2010 will be an amazing time yet again.

Happy New Year and as usual, Happy Coding!

Laurent

Silverlight 4: Drag&drop with EventToCommand

One of the MVVM Light Toolkit’s user requested that I add the possibility to pass the EventArgs of an event to the ICommand that it is bound to through the EventToCommand trigger. At first I was a bit reluctant because it seems like a transgression of the rule that says you should avoid to have too much knowledge about the UI layer in the ViewModel. For example, if you have a RelayCommand in the ViewModel that expects a MouseEventArgs, it kinds of binds you to a certain kind of UI element, which is not super clean.

That said, I also understand that in some cases it might be useful to get the EventArgs down in the ViewModel, which is why I decided to add this possibility (available from V3/alpha 3).

And in fact, as I was testing it, I just got another request from my good friend Laurent Kempé (one of the early and enthusiastic users of MVVM Light) to help use EventToCommand in the case of a drag&drop operation in Silverlight 4. That was the perfect test case for this new feature.

Note: Laurent wrote a post in French describing a drag&drop implementation.

Resources

The source code for this sample is available here. The MVVM Light Toolkit’s DLLs are also included (V3/alpha3). This code is for Visual Studio 2010 beta 2 and/or Expression Blend Preview for Silverlight 4.

You can optionally install the MVVM Light Toolkit V3/alpha3 from the Installing Manually page.

More info about the MVVM Light Toolkit is available on the Get Started page.

Creating a drag&drop enabled Silverlight application

Let’s start by creating a new MVVM Light application in Silverlight 4. In the moment the process of installing the project templates is manual, but it should be easy enough if you follow these instructions.

  • You can create a new MVVM Light application for Silverlight 4 in Visual Studio 2010 or in Expression Blend Preview 4. Simply choose File, New Project and then select the template called MVVM Light (SL4).

We need to define a drop target for the files in the application. This can be done for just any UI element, so you can choose the main Grid (if you want the whole application to be a drop target) or any other element. In our case, to keep things simple, let’s define the main Grid as the drop target.

  • Set the property AllowDrop to True, either in XAML or in Blend. Also change the other properties as shown in XAML below.
    Note: We will implement the DroppedFileContent property in a moment.
<Grid x:Name="LayoutRoot"
      AllowDrop="True"
      Background="#FF9F9F9F">
    <TextBlock FontSize="36"
               FontWeight="Bold"
               Foreground="Purple"
               Text="{Binding DroppedFileContent}"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               TextWrapping="Wrap"
               TextTrimming="WordEllipsis" />
</Grid>

  • Open the MainViewModel and add a bindable property.
    Note: If you have the MVVM Light Toolkit installed, you can use a code snippet for this: Type mvvminpc then tab to expand the snippet, and enter the property’s name, tab, its type, tab and the name of the attribute. Then, edit the code until it looks like the one below:
/// <summary>
/// The <see cref="DroppedFileContent" /> property's name.
/// </summary>
public const string DroppedFileContentPropertyName = "DroppedFileContent";

private string _droppedFile = "Drop file here";

/// <summary>
/// Gets the DroppedFileContent property.
/// Changes to that property's value raise the PropertyChanged event. 
/// </summary>
public string DroppedFileContent
{
    get
    {
        return _droppedFile;
    }

    set
    {
        if (_droppedFile == value)
        {
            return;
        }

        _droppedFile = value;
        RaisePropertyChanged(DroppedFileContentPropertyName);
    }
}
  • Add a RelayCommand<DragEventArgs> property to the MainViewModel. Name this property HandleDropCommand. You will need to add GalaSoft.MvvmLight.Command, System and System.Windows to the “using” section.
public RelayCommand<DragEventArgs> HandleDropCommand
{
    get;
    private set;
}
  • Finally, in the constructor, initialize the HandleDropCommand. We will start by simply showing a MessageBox when a file is dropped.
public MainViewModel()
{
    HandleDropCommand = new RelayCommand<DragEventArgs>(e =>
    {
        System.Windows.MessageBox.Show("Drop");
    });
}
  • Add an EventToCommand trigger to the main Grid. This element is part of the GalaSoft.MvvmLight.Extras DLL which is referenced by default in the MVVM Light project template, so if you start like we described here, you don’t need to do anything to use EventToCommand. If you start from a non MVVM Light application, you need to add a reference to GalaSoft.MvvmLight.dll, GalaSoft.MvvmLight.Extras.dll and System.Windows.Interactivity.dll
    Make sure you get the V3/alpha3 version.
    Make sure you reference the binaries from C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\VS10\Binaries\Silverlight).
    • Build the application to make sure that you have the latest stand loaded in Blend.
    • In Blend, open the Assets tab, select the EventToCommand from the Behaviors category and drag/drop it on the LayoutRoot grid.
    • Then set the EventName property to “Drop”.
    • Bind the Command property to the HandleDropCommand in the MainViewModel which is the Explicit Data Context of the main Grid.
      Note: To open the databinding editor, press the advanced properties widget (the small black square) next to the Command property, and select Data Binding from the context menu.

 

    • Finally, check the PassEventArgsToCommand checkbox.
      Note: The combination of having an argument of type EventArgs in the RelayCommand, and the PassEventArgsToCommand property set to true will cause the event’s EventArgs to be passed directly to the RelayCommand’s parameter.

 

  • If you do not have Blend, you can also add the EventToCommand in Visual Studio in XAML:
    • In the MainPage.xaml file, add two namespaces to the UserCommand tag:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

 

    • Then, add the EventToCommand trigger within the LayoutRoot grid with the following XAML code:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Drop">
        <cmd:EventToCommand Command="{Binding HandleDropCommand, Mode=OneWay}"
                            PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

 

  • Test the application: In Blend, press F5, or in Visual Studio press Ctrl-F5. Then, drag a file, and drop it on the main Grid. Notice how the mouse cursor indicates that the Grid is a valid drop target.

 

  • Drop the file. You should see the MessageBox proving that the RelayCommand has been called successfully.

Getting and handling the files

Now that we have the RelayCommand ready, let’s access the DragEventArgs and get the file content from there. In this sample example, we will accept TXT files, and display the first few words from the file content.

  • Replace the call to MessageBox within the HandleDropCommand implementation with the following code:

if (e.Data == null)
{
    return;
}

var files = e.Data.GetData(DataFormats.FileDrop)
    as FileInfo[];

// This works with multiple files, but in that
// simple case, let's just handle the 1st one
if (files == null
    || files.Length == 0)
{
    DroppedFileContent = "No files";
    return;
}

var file = files[0];

if (!file.Extension.ToLower().Equals(".txt"))
{
    DroppedFileContent = "Not a TXT file";
    return;
}

using (var stream = file.OpenRead())
{
    using (var reader = new StreamReader(stream))
    {
        // Read the first line
        var line = reader.ReadLine();
        DroppedFileContent = line;
    }
}                

Few notes about this code:

  • You can get a reference to the files dropped on the target with the DragEventArgs.Data.GetData method.
  • Note however that since we are in Silverlight within the security sandbox, you will get a security exception if you try to access the file’s FullName. You may get the content of the file (because it is dropped by the user) but not additional information about where these files are located.
  • In this example, we get only the first file, but it is easy to see how we could access all the files dropped.
  • We do handle only TXT files in this example.
  • Reading the file’s content is done in an usual way, with a Stream and a StreamReader. Note the presence of the “using” statements, to make it easier (no need to explicitly close and dispose the stream and the reader). For binary files, we would use a BinaryReader, etc…

An issue with Visual Studio 2010

In the course of preparing this article, I noticed an issue in Visual Studio 2010 when I attempt to debug the HandleDropCommand implementation. Even with a breakpoint placed within the code, the debugger does not break. I am not sure right now what is the reason, and the code does get executed, but this complicates debugging of course. I am investigating and talking to Microsoft about that, but right now I am not sure where it comes from.

Conclusion

In the MVVM pattern, we generally try to avoid putting too much code in the code behind because it complicates the developer-designer workflow. Though I am not a puritan about that :) I think that EventToCommand and the new PassEventArgsToCommand property are reasonable steps to make UI interaction such as drag&drop even easier to code.

Hope you like it :)

 

MVVM Light V3/alpha3 for Blend 3 and Blend Preview 4

The project and item templates allowing you to create pre-wired MVVM Light applications are now also available for Expression Blend 3 and Expression Blend Preview for .NET 4 and Silverlight 4. The installation process is manual, but not difficult at all (unzipping a few files to predefined paths). I did document the installation process here.

Of course the templates are also available for Visual Studio 2008 and Visual Studio 2010, as well as the binaries. The source code is available on Codeplex.

I still have one feature I want to add in V3, and then I will create a release version. Seeing how my schedule is, it will probably be during the holidays. However, V3/alpha 3 is very stable and I didn’t get any error report from users who upgraded. I also don’t think there will be any breaking change. At this point, I would recommend users who want the new features to upgrade to V3.

I will post a list of new features in this version later.

Happy coding!


MVVM Light V3 in Blend Preview for .NET 4 and Silverlight 4

 

One year at IdentityMine

Today it is exactly one year that I started work at IdentityMine, after 13 years at Siemens (well, Staefa Control System then Landis&Staefa then Siemens through a series of acquisitions, ah the joys of corporate world…). Here is a link to the article where I related my decision to leave Siemens and to join IdentityMine.

One year later, I realize that I worked on 14 different projects (not mentioning those where my participation was limited to a simple phone call to a client or to the team). This is quite different from my time at Siemens, where I worked mostly on one huge project during 2 or 3 years! I have to say I enjoy this a lot, the change is welcomed and the diversity. I have worked on projects in WPF, Silverlight and Surface, and I consider myself extremely lucky to have the chance to program on such advanced technologies.

My focus at IdentityMine has been primarily as an Integrator (I have the chance to work as part of a small group of very talented individuals, Nathan Dunlap (who keeps amazing me with his Ninja skills), Frank Preuss and Jesse Hsia. We are a very small group and correspondingly active in various projects. The integrator role, located right between the designers and the developers, corresponds perfectly to my interests, and I spend a lot of time into Expression Blend, my favorite tool. That said, I keep coding too, and I am very psyched to be already working on some Silverlight 4 projects in Visual Studio 2010!!

What I love most at IdentityMine is how they make me feel that I am really a member of the family even though my location is remote. As the only European employee, it is really something I need, to communicate a lot with the mothership (and also with my colleagues in India, where we have a solid team of great devs and designers too!). Funny to say, but I never felt lonely or treated differently. And of course the occasional trip to Seattle totally helps to build the team spirit.

(Side note: We live an amazing time. I have an IP phone with which I can call Seattle at no cost, MSN to chat while coding, Twitter and Facebook to replace the coffee corner and keep up to date with the gossips… I dare say I know some of my colleagues at IdentityMine better after one year working remote than many of my ex-Siemens colleagues after 13 years of going to the office…)

So what do we have in store for the future? Well, tons and tons of amazing projects, that’s for sure. Also, with the incredible love that is shown to Silverlight 3 (and 4…) in Europe right now, I think the time has come to expand our activities here, and this is definitely something we are talking about. The timeline is unknown, mostly because growing a team is not something that should be done without careful considerations (the well being of the employees counts a lot, so we’re very careful to make sure everything is considered). In the mean time, we continue helping our customers to create beautiful applications, and more than ever, we love our code!

MVVM Light Toolkit V3 Alpha 3 for WPF4/SL4

Update: The templates are also available for Expression Blend 3 and Expression Blend Preview for .NET 4 and Silverlight 4.

4084199726_d1cc8527aa_o[1]

I just published the latest alpha version of the MVVM Light Toolkit. I will post more about the new features in this alpha version, but the most exciting is probably that with this release, the MVVM Light Toolkit works in Windows Presentation Foundation 4 and in Silverlight 4 (in Visual Studio 2010).

There is no automatic installer for this version yet, but I wrote a page describing how to install manually (it is as easy as unzipping a few files). All the features are also available for Visual Studio 2008 as usual.

The source code was also updated on the Codeplex website.

More documentation will follow soon so stay tuned. In the mean time, have fun with MVVM in WPF4/SL4!

 

My talk at #notatpdc postponed

Hey guys,

I am really sorry for having to postpone my talk about Expression Blend 3 and SketchFlow. We had some huge difficulties with the NotAtPDC.com website, and unfortunately we were not able to locate the site administrator on time to solve the issue. Without a speaker login, I was able to talk to the attendees, but not share my desktop. Now I love to talk about Blend but I love even more to show Blend ;)

Ironically, as a Microsoft MVP I do have a LiveMeeting account, so I would be able to host the talk myself, but organizing a LiveMeeting take a little time, and I didn’t want to rush into that, cut my talk short or step on the next speaker’s feet (let’s hope that the issues get solved in time for him!)

We will definitely reschedule the talk, either within NotAtPDC (if we find a suitable time slot) or a bit later, so definitely stay tuned on this blog and my twitter feed for more info.

Silverlight 4 beta released at #PDC09

Well people, it was an amazing keynote. Silverlight 4 beta was just presented by Scott Guthrie at the Professional Developer Conference 2009 in Los Angeles. As soon as Silverlight 3 was released a few months ago, the Silverlight team started working on new features to create what will be a really exciting release.

As of now, the Silverlight 4 beta bits and all the necessary tools are available for download. Probably the best place to start is Tim Heuer (Silverlight evangelist for Microsoft) who has a guide to the new features on his blog. A great and very clear read!

Another fantastic resource is my friend Corrado Cavalli’s PDF document with all the new features (there is also an Italian version on Corrado’s blog).

Update: Just found out about the Silverlight 4 Training Course available on Channel 9, put together by Adam Kinney and John Papa, two Microsoft evangelists!

What happens with WPF?

Those of you who know me well know that I love WPF as much as Silverlight, and I am really super happy to work for IdentityMine, a firm that is very active in both environments.

Windows Presentation Foundation is not dead, not at all. With WPF4 (which is available in beta with Visual Studio 2010 beta 2), a load of new features is making it to the desktop as well. In the beginning of the year at MIX09, I had a talk about the .NET continuum, and we are exactly there, with Silverlight and WPF coming closer, but still having their respective features. WPF is more than ever Silverlight’s big sister, they are closer than they have ever been, which is a blessing for us developers because passing from one world to the other has never been easier.

With Silverlight running out of the browser with elevated permissions, and with the possibility to modify the appearance of the window hosting the out-of-browser application, Silverlight is coming very close to a desktop application. But it is not one yet. So the question is, will we see a “merge” between Silverlight and WPF in the coming few years? Well to be frank, I am a very vocal proponent of the convergence, and I am pretty sure that we will go that way sooner or later. The good news is that all that Microsoft learned over the years while creating WPF is invested in Silverlight. In some areas, it has been made even better, because they learned from some mistakes. In others, they capitalized on the fantastic functionalities available in WPF and made that available to us without a change in Silverlight. My point is that talking about the death of WPF is a cow’s opinion, it’s a moo point. WPF and Silverlight will continue to grow ever closer, and we will continue to enjoy the best of both worlds, the desktop and the web! Exciting years to be a client developer indeed!

These are YOUR features

One thing the Silverlight does really well is listen to the community. I read somewhere that 70% of the features requested by the community have made it into Silverlight 4 beta. This is pretty amazing. So continue that work, place your requests either directly to Microsoft evangelists if you have the chance to know one, or through Silverlight MVPs who have possibilities to get to talk to the Silverlight team often.

And the story is not over yet… Keep your eyes open, we have amazing years in front of us!

Happy coding!!

 

Talking at #notatpdc about Blend 3 and SketchFlow

notatpdc09sm[1]

NotAtPDC is an awesome initiative from within the .NET community that allows people who cannot for any reason attend one of the major conferences (such as PDC, MIX etc…) to share knowledge, have fun, interact and generally have all kind of good times without leaving their home or office.

This year, I cannot make it to the Professional Developer Conference because of multiple reasons (too much work, too many travels ;)) but I will talk to the NotAtPDC conference 2009!

My talk is titled Expression Blend 3: From Design to Realization and is scheduled at 11AM CST on 2009/11/19 (see below for the time at your location).

When designers envision beautiful applications, and pass the comps to developers for realization, the result is often not really up to their expectations. Expression Blend stands between the designer and the developer, and facilitates the workflow. It is not "just" a design tool, it is a visual development environment! In this session, we will show you new features in Expression Blend 3, such as the "interactive sketching tool" SketchFlow and more. This session will take a deep look at the new Blend 3 features such as SketchFlow, Photoshop import, Design-time data, etc…

I am really looking forward to giving this talk, which should be a lot of fun. Let’s face it, Blend 3 is awesome and taking a good in-depth look at the great features that are included in V3 should prove valuable to designers AND developers.

Thanks a lot to Steve Andrews, Rachel Appel and all those who take some of their precious free time to organize this event!

Logging in the session

You need LiveMeeting to log in the session. Make sure you download and test LiveMeeting in advance! The direct link to the session for attendees is:
https://www.livemeeting.com/cc/usergroups/attend?id=F98RD3&pw=Pa$$w0rd

Location Date/Time
Pacific Standard Time Thu, 11/19/2009, 9AM
Mountain Standard Time Thu, 11/19/2009, 10AM
Central Standard Time Thu, 11/19/2009, 11AM
Eastern Standard Time Thu, 11/19/2009, 12PM
London Thu, 19th Nov 2009, 17:00
Paris, Zurich, Milano… Thu, 19th Nov 2009, 18:00

Should your location not appear in this table, my apologies, make sure you check the World Clock Converter to avoid missing the start of the session :)