MVVM Light Hotfix for Windows Phone 7 developer tools beta

4084199726_d1cc8527aa_o[1]

This is a hotfix to correct the issues with the MVVM Light templates for Windows Phone 7.

Who is it for?

Use this hotfix if (and only if):

Why a hotfix?

The hotifx is needed because of changes in the Microsoft Windows Phone 7 assemblies (regrouping of classes in different namespaces and/or different assemblies) as well as some other changes (manifest structure, etc). The MVVM Light assemblies do not need any update however, and continue to work as expected with the new release.

How to install?

The installation process is described at http://www.galasoft.ch/mvvm/installing/hotfix20100719/

Note about Blend:

At the moment, Blend for Windows Phone beta seems unable to load custom template. I have a pending question with Microsoft to try and clear this up. Right now, the workaround is to create the MVVM Light application for Windows Phone 7 in Visual Studio, and then to open it in Blend for Windows Phone beta.

Happy coding!

Laurent

 

JavaScript vs Silverlight: An answer

An article was published at JupiterJS.com (titled “JavaScript vs Silverlight”) arguing that JavaScript is better than Silverlight. Unfortunately, there is no way to post comments on that page (weird, really) so I decided I would post my answer here.

First let me state that I do not think that Silverlight is an opponent, nor a threat to JavaScript. I love both, I write both, and both are helping me to create better experiences.

Also, Silverlight has grown to be much more than “just” a web plug-in. You can write out-of-browser applications for PC and Mac, and now you can use it to write Windows Phone 7 applications. In the near future it will expand to other platforms (top boxes, etc). So opposing JavaScript to Silverlight is really shooting at the wrong target in my opinion.

That said, some (many) of the points in this article are wrong and need correction, so here goes:

  • Plugin Lock-In: OK I will grant that one. The number of users according to the article is 50%, Microsoft speaks of 65% (I think, didn’t check the latest), but all in all you’re right, it is less widespread than JavaScript. The fact that it took years to JavaScript to reach that broad reach and that level of standardization is irrelevant right now, since we are in the present and not the past. This is an argument for what I have been advocating always: Use Silverlight to enhance your webpage, not to replace it completely.
  • HTML5: Quoting: “HTML5 is going to provide a lot of the same goodies that Silverlight provides.” Keywords: “is going”. Where do I start… first it is really not ready yet. Let’s talk about it in 2 years or 5 years. Second, even though it is developed as an open standard, nothing says that the browser makers will implement all functionalities in the same way and in the same time frame. I have been burnt too much in the past to trust the words of corporations when it comes to implementing “standards”. On the other hand, you know exactly what you get with Silverlight.
  • Group Standards: See “HTML5”.
  • Competition: Since when is that a bad thing? Competition encourages innovation, and Flash/Flex have pushed Silverlight to become bigger and better in a ridiculously short timeframe. Besides, HTML5 is also a competition to Flash and Silverlight and others, so the same story applies here.
  • Backend locking: First, why talk about Flex here? Was this article initially aimed at Flex? Weird… anyway, when it comes to Silverlight, nothing could be more wrong. SOAP-based services are just one option. With Linq-to-Json and Linq-to-XML, parsing JSON and XML based replies is a breeze and much easier (and faster) than in JavaScript. Believe me, I know, I did wrote a lot of parsing code for JavaScript when it was all we had.
    In fact, Silverlight is so good at REST calls and networking that I would recommend using Silverlight (where available) to do that even if you do not use XAML to create a UI. Use the HTML Bridge to communicate back and forth with JavaScript, and use the speed and ease of use of Silverlight for the heavy lifting.
  • Development time: Visual Studio is the best development environment available, and that pretty much sums it up. Firebug is great, but I really prefer a full blown debugger. I understand it is a matter of preference to a certain point.
  • Open: As someone who writes and maintains open source projects, and a rich blog, I know that there is a lot of open source projects and of documentation available online. I rarely use the Microsoft official documentation if I want to solve something, I either get an open source component to perform the task, or I find how to do it myself, with the added value of learning something in the process.
  • Community: I have been active in the JavaScript community and I have been active in the Silverlight community, and I loved both. I am more active now in the Silverlight community because it is where I spend most of my time. It is a rich, vibrant and innovative community, and I love every moment I spend interacting with it.
  • Scripting vs Compile: We could argue for hours about that. I love C# as a language, so I am glad I can use it in Silverlight. That said, you can also use Python, Ruby and more if you prefer. As for the fact that scripting produces less code, I am puzzled. I doubt it. Maybe if you ignore the fact that jQuery is of course code, and needs to be interpreted too. In that matter, Silverlight wins, since the .NET framework is not interpreted, but is already there and optimized, ready to be used. Also, compiled code is still faster than the fastest JavaScript, though to be honest I never really found that to be an issue when I was writing a lot of JS code.
    Also, I feel that it is easier to write clean decoupled code in Silverlight than in JS. Componentizing an application with MEF or an IOC framework is super easy. .NET wins here in my book.
  • Testing: Silverlight has at least two unit test frameworks that I know of, the Silverlight Unit Test (part of the Silverlight toolkit, available for free and super easy to use) and NUnit. As for automated UI testing, it is also possible.
  • In the box: What I usually advocate is “island of richness” made in Silverlight than communicate with the rest of the page. I am not a huge fan of full pages made in Silverlight. These island of richnesses can communicate with JavaScript (through the HTML bridge) or with other Silverlight applications running in the same page or in another page (local communication). It is as open as I need it to be. Also, Silverlight applications (in the contrary of other plugins) can blend with the HTML if needed, and you can place HTML elements in front of a Silverlight area. It does not need to be square, by the way, you can clip it to any shape. Here too, I consider the fact that I can use JavaScript (should I need it) an advantage.
  • Perceived performance: As said before, it is now super easy (with MEF) to componentize a Silverlight application and load modules on demand. It is also possible to write customized splash screens, so the UX is better should the loading time be slow anyway. Oh, and I can use JavaScript to start performing tasks while waiting ;) best of both worlds.
  • Mobile: iPhone, I agree. It’s funny to have to use a closed platform as an argument for openness ;) but yeah, as long as Jobs doesn’t come to his senses, Silverlight won’t make it to iPhone. This kind of things should actually make you want to sell your iPhone and choose a better phone, but this is another debate. For now, for mobility with Silverlight, I will use Windows Phone 7 and am very excited about it. There is also Silverlight on Symbian, and I wouldn’t be surprised to see it run on Android too some day.
  • OS Support: As I said, the numbers cited by MSFT are higher than 50%, but since noone really knows, I will happily concede that JavaScript’s reach is larger. That said, Silverlight runs on multiple flavors of Windows (included embedded for kiosks etc), Mac, Linux (it runs pretty well there, Miguel and his team are doing a great job), plus all the other platforms to come (Windows Phone, top sets, etc). Yes JavaScript wins in terms of reach, which makes it a great fallback strategy.
  • Accessibility: The accessibility story is much better in Silverlight 4 and this is an area where the team is constantly improving. Already now, it is possible to make selectable rich text boxes. If you want to display HTML content on top of Silverlight, you can. Also, this really has nothing to do with JavaScript, you’re comparing Silverlight to HTML here.

Anyway… my point still stands: Both technologies complement each other. Silverlight plays very well with JavaScript, and an SL application is really not the isolated ivory tower that the article paints. It has multiple ways to interact with the page, with JavaScript and with the web.

It is also a platform that is a lot of fun to develop for, and allows for a great user experience. It enables my designers to think out of the box and we constantly push them to try new concepts. No more square boxes, easy multitouch interactions, rich and smooth hardware accelerated animations and much more make Silverlight a really great platform to code for. So dear reader if you made it that far, do not let ill-informed articles lure you away from Silverlight, at least give it a try and if you have something that you don’t understand, ask the community, it is great!.

Oh, and if you disagree, please post a comment below (but keep it civil and constructive ;) This is what the community is about, discussing and interacting!

Cheers,

Laurent

 

MultiTouch Behavior: Update for Windows Phone 7 tools beta

Update: The second video (10’ tutorial) is now ready (see below).

Update 2: The code is on Codeplex (V0.5.1).

I just published an updated videos (Highlights) showing the MultiTouch Behavior for Windows Phone 7 working with the new emulator. The big change is that the multitouch action now works great with the emulator (with the April CTP it was flaky, so I was using the mock mode a lot more). Another 10’ long tutorial is available.

The code on Codeplex has been updated, so that all of you with the new tools can enjoy the new libraries as well as the sample application running in the beta emulator!!

As before, more information is available on http://www.galasoft.ch/Touch !!

Cheers,

Laurent

Highlights

Tutorial

 

How to use the MultiTouch Behavior for Windows Phone 7

Yesterday, I published the source code of the MultiTouch Behavior for Windows Phone 7 on Codeplex (http://multitouch.codeplex.com). Meanwhile, Davide Zordan (the founder of this project) started to modify the Silverlight 4 version of the behavior to make it API compatible. Eventually, the goal is to share all the API signature, and as much code as possible. We would like to extend this to the WPF version as well, in order to have a consistent landscape of multitouch on all 3 platforms.

Together with the source code, you will also find an automated setup file (MSI) that copies the DLLs to c:\program files, but also creates a registry entry that makes the MultiTouch Behavior available in Expression Blend even though the references have not been added yet. This makes adding everything needed in your WP7 application as easy as drag and drop.

There are two tutorials available:

  • A 15’ long video (embedded below) where I show how to use the behavior and how it works.
  • In addition, I just published a written tutorial that explains how to add the behavior in Blend and in XAML, as well as documenting all the properties.

With all that, you should be set! I would love to get feedback, so please if you find a bug, or have constructive suggestions, talk to me!! :)

Cheers,

Laurent

Figure 4: Debug mode and visualize fingers

 

MultiTouch Behavior for Windows Phone 7: Videos #wp7dev

I just published two videos on Vimeo (see the embedded videos at the end of this post)

  • One is a short video showing the highlights of the MultiTouch Behavior I have been working on. It shows what gestures are available, and how easy it is to add it to a Windows Phone 7 application.
  • The other is a detailed 15’ video that explains exactly how the behavior can be used.

I am still polishing a few things up and should be ready to release V1 on Codeplex very soon.

Features:

  • Scale, Rotate, Translate are supported.
  • Possibility to show markers on the screen for demos/projections/videos.
  • Debug mode with addition on-screen information.
  • “Mock” mode for development without multitouch screen. Simulate fingers with just one mouse.
  • Enable/disable Scale, Rotate, Translate X and Y individually.
  • Constrain Scale with minimum and maximum value.

Future plans:

Not supported (but in the plan) are:

  • Multiple elements: Right now, the gestures can only apply to one element on the screen.
  • Friction/inertia.
  • Constraining the element to the screen.

More info

I will post more info as we progress. Stay tuned to this blog (“touch” tag), on my website http://www.galasoft.ch/touch or on Twitter (@LBugnion).

Credits

I want to thank Pete Blois (from the Microsoft Expression Blend team) for his help and some of the multitouch code, and the kind permission to open source it.

Also heartful thanks to Davide Zordan for starting this project on Codeplex and for the inspiration.

The Videos

2'50'' highlights



15' walk through

 

Silverlight 4 Unleashed table of content

Silverlight 4 Unleashed book cover

(book cover might change before publication)

As I am reaching the end of the writing phase of Silverlight 4 Unleashed (to be published at Sams), I thought I would give a little more information about this book.

The book’s idea

Because I didn’t want to merely write an update to the existing Silverlight 2 Unleashed, I proposed a different approach to my editor: Using Silverlight 2 Unleashed (which was bringing people up to speed with Silverlight 2 pretty much from scratch) as the basis for the new book, and building on the foundation. The thing is, much of the material from Silverlight 2 Unleashed is still valid in Silverlight 4. There are very few differences and of course all the new features that were added in SL3 and SL4, but let’s face it, I don’t have much new to write about XAML, the basic transforms, animations etc.

We decided to make the PDF of selected chapters of Silverlight 2 Unleashed available to the buyers of Silverlight 4 Unleashed. This way, developers who never touched Silverlight will be able to bring themselves up to speed, and then to dive into advanced material with the new book. We still need to work out the exact details, more about this later. I think this is an innovative and attractive initiative, and I am very grateful that Sams accepted to do this.

With that, it means that Silverlight 4 Unleashed will be 700+ pages packed with brand new material. Some of the features I describe were already available in Silverlight 3, but you will need them for Silverlight 4 (and since we didn’t do a Silverlight 3 version of the book, they needed to be mentioned). I think I did a good job in covering most of the features that Silverlight 4 has.

Just like my first book, this new book is chock-packed with code samples (everything will be available on my website, of course) and pictures. We are also renewing the Silverlight 2 Unleashed experience by publishing the new book in full color. I am very happy about this again (and let’s be honest, this is a lot of work for me as an author and for the editor too to do a book in color), and I think the added value is pretty obvious.

The topics

A full table of content is available as PDF. There are 22 chapters as shown below.

Caveat: This is a raw TOC. Some chapters (title and content) will change during the edit process. Early chapters were written against Silverlight 4 beta, so some names will change before publication.

Introduction

  1. Three years of Silverlight
  2. Setting up and discovering your environment
  3. Extending your application with controls
  4. Investigating existing controls
  5. Understanding dependency properties
  6. Grouping, sorting and binding
  7. Understanding the Model-View-ViewModel pattern
  8. Using data controls
  9. Connecting to the web
  10. Creating resources, styles and templates
  11. Deep diving into Blend
  12. Sketching user experience
  13. Creating line of business applications
  14. Enhancing line of business applications
  15. Developing navigation application and Silverlight for Windows Phone 7
  16. Using effects and recording media
  17. Extending the experience
  18. Extending the experience some more
  19. Extending the experience (again)
  20. Building extensible and maintainable applications
  21. Optimizing the performance
  22. Using advanced development techniques

Conclusion

When will it be available?

I often get asked when the book will be available. My answer has been: After the summer. We didn’t decide the exact date of publication yet, but rest assured that both Sams and I are doing all we can to have this book out to you guys as soon as possible, and with the highest possible quality.

For more info about the book’s progress, follow me on Twitter and stay tuned to this blog!

Happy coding,

Laurent

 

Windows Phone 7 multitouch behavior: beta testers needed (#wp7dev)!

I finished implementing version 0.1/beta1 of a multitouch behavior for Windows Phone 7 and need beta testers.

What is the Windows Phone 7 multitouch behavior?

Multitouch in Windows Phone 7 is not super hard, but there are a few things that need to be taken in account (such as the orientation of the device). In addition, it is very easy to get unwanted effects on a small screen (for example that the element becomes too big/too small). Also, in some cases the proportionality should be kept for a scaled element. The multitouch behavior encapsulates all these concerns and expose a set of easy-to-understand properties to govern its usage. These properties can be databound, so you can even change their value during runtime.

In addition to this, the multitouch behavior has two modes that make it easier to debug a multitouch application:

  • A debug mode, in which debug information is written to the screen. This is super useful because it is really hard to debug a multitouch application. Setting breakpoints interrupts the manipulation! Having the debug info on the screen helps to understand why things are not working exactly as you want.
  • A visualization of the first finger that was pressed on the screen. This is especially useful for demos, where the audience does not see your fingers on the screen of the emulator. It is also useful when debugging. The finger is represented by a small orange ellipse drawn on the screen and moving as you move your finger.

Notes:

  • I was not able to test on a real device yet. Microsoft, if you listen, writing multitouch code without a real device to test is super hard. You know I am a good guy, and I share my knowledge, please give me a development device… thanks!
  • The visualization of the pressed finger works only for one finger at this time. More fingers should be visible in a further version.

Where will you publish it?

The multitouch behavior for Windows Phone 7 will be published on Codeplex, in the awesome project started by Davide Zordan that aims to provide a unified interface for multitouch in Windows Presentation Foundation, Silverlight and Windows Phone 7.

What is supported (and what is not)?

The following is supported in this first version:

  • Translate manipulation: move an element on the screen.
  • Scale manipulation: Use a “pinch” gesture to zoom an element in and out.
  • Maximum and Minimum scale (optional): Avoid that an element becomes too large or too small.
  • Proportional scale: Forces an element to stay proportional along the X and Y axis, no matter what.
  • Debug mode (see above).
  • Finger visualization (see above).
  • Automatic support for orientation change.

Not supported:

  • Rotate manipulation: this is not supported by the Windows Phone 7 Silverlight framework at this point. We are hoping to support it anyway in a future version, but it is unclear how.
  • Inertia: in this version, inertia is not supported. We are hoping to get inertia working in a future version.
  • I was not able to test the behavior when the device is held upside down. For the moment, this mode is not explicitly supported until I have a device where I can make sure that it works fine.

How do I know if I can apply?

You need the following to test the multitouch behavior:

  • A computer with the Windows Phone tools (April CTP) installed.
  • The computer’s screen must support multitouch (at least two points)
  • You must make sure that the Windows Phone 7 emulator does indeed support multitouch on your computer (see below).
  • (optional) you have access to a Windows Phone 7 device and can run applications on it.

How do I make sure that the Windows Phone 7 emulator supports multitouch on my computer?

Apparently not every multitouch computer supports multitouch in the Windows Phone 7 emulator. We heard that the PDC laptop (that was given to PDC attendees in 2009) does not support multitouch in the emulator.

To know if your multitouch computer qualifies is very easy with the following steps:

  1. Create a new Silverlight for Windows Phone 7 application in Visual Studio, Visual Studio Express or Expression Blend.
  2. Start the application.
  3. In the emulator, press on the Windows button to go back to the start screen.
  4. Press on the Internet Explorer tile.
  5. Navigate to a web page and try to zoom in using a pinch gesture.

If you are able to zoom in and out using the pinch gesture, your computer should be able to test the Windows Phone 7 multitouch behavior!

How do I apply?

Very simple: Send me an email (laurent@galasoft.ch) or send me your email address on Twitter (@lbugnion). I will send you a test application, instructions to make it work and a few questions that I would like you to answer to understand how the experience worked for you, and how it could be improved.

I will also be looking for people willing to write documentation (articles, etc…) for this component, so if you have the soul of a writer and have an outlet (blog, Code Project, etc) let me know and I will send you the preview code.

What’s next?

I am hoping to publish the code on Codeplex very soon after I get enough feedback. Of course all announcements will be made on this blog too, so stay tuned.

Pictures

 
Debug mode in multitouch behavior

 
Visualization of finger

 
Debug mode and visualization of finger

 
Settings of sample application

Happy coding!

Laurent

 


					
				

Two small issues with Windows Phone 7 ApplicationBar buttons (and workaround)

When you work with the ApplicationBar in Windows Phone 7, you notice very fast that it is not quite a component like the others. For example, the ApplicationBarIconButton element is not a dependency object, which causes issues because it is not possible to add attached properties to it.

Here are two other issues I stumbled upon, and what workaround I used to make it work anyway.

Code to demonstrate the issues and the workaround can be downloaded here!

Finding a button by name returns null

Since the ApplicationBar is not in the tree of the Silverlight page, finding an element by name fails. For example consider the following code:

<phoneNavigation:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBar.Buttons>
            <shell:ApplicationBarIconButton
                IconUri="/Resources/edit.png"
                Click="EditButtonClick"
                x:Name="EditButton"/>
            <shell:ApplicationBarIconButton
                IconUri="/Resources/cancel.png"
                Click="CancelButtonClick"
                x:Name="CancelButton"/>
        </shell:ApplicationBar.Buttons>
    </shell:ApplicationBar>
</phoneNavigation:PhoneApplicationPage.ApplicationBar>

with

private void EditButtonClick(
    object sender, 
    EventArgs e)
{
    CancelButton.IsEnabled = false;
    // Fails, CancelButton is always null
}

The CancelButton, even though it is named through an x:Name attribute, and even though it appears in Intellisense in the code behind, is null when it is needed.

To solve the issue, I use the following code:

public enum IconButton
{
    Edit = 0,
    Cancel = 1
}

public ApplicationBarIconButton GetButton(
    IconButton which)
{
    return ApplicationBar.Buttons[(int) which]
        as ApplicationBarIconButton;
}

private void EditButtonClick(
    object sender, 
    EventArgs e)
{
    GetButton(IconButton.Cancel).IsEnabled = false;
}

Updating a Binding when the icon button is clicked

In Silverlight, a Binding on a TextBox’s Text property can only be updated in two circumstances:

  1. When the TextBox loses the focus.
  2. Explicitly by placing a call in code.

In WPF, there is a third option, updating the Binding every time that the Text property changes (i.e. every time that the user types a character). Unfortunately this option is not available in Silverlight). To select option 1, 2 (and in WPF, 3), you use the Mode property of the Binding class.

The issue here is that pressing a button on the ApplicationBar does not remove the focus from the TextBox where the user is currently typing. If the button is a Save button, this is super annoying: The Binding does not get updated on the data object, the object is saved anyway with the old state, and noone understands what just happened.

In order to solve this, you can make sure that the Binding is updated explicitly when the button is pressed, with the following code:

private void SaveButtonClick(object sender, EventArgs e)
{
    // Force update binding first
    var binding
        = MessageTextBox.GetBindingExpression(
            TextBox.TextProperty);

    binding.UpdateSource();

    // Property was updated for sure, now we can save
    var vm = DataContext as MainViewModel;
    vm.Save();
}

Obviously this is less maintainable than the usual way to do things in Silverlight. So be careful when using the ApplicationBar and remember that it is not a Silverlight element like the others!!

Happy coding!

Laurent

 

Handling DataGrid.SelectedItems in an MVVM-friendly manner

An interesting question from one of the MVVM Light users today:

Is there an MVVM-friendly way to get a DataGrid’s SelectedItems into the ViewModel?

The issue there is as old as the DataGrid (that’s not very old but still): SelectedItem (singular) is a DependencyProperty and can be databound to a property in the ViewModel. SelectedItems (plural) is not a DependencyProperty.

Thankfully the answer is very simple: Use EventToCommand to call a Command in the ViewModel, and pass the SelectedItems collection as parameter. For example, if the command in the ViewModel is declared as follows:

public RelayCommand<IList> SelectionChangedCommand
{
    get;
    private set;
}
and (in the MainViewModel constructor):
SelectionChangedCommand = new RelayCommand<IList>(
    items =>
    {
        if (items == null)
        {
            NumberOfItemsSelected = 0;
            return;
        }

        NumberOfItemsSelected = items.Count;
    });

Then the XAML markup becomes:

<sdk:DataGrid x:Name="MyDataGrid"
                ItemsSource="{Binding Items}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand
                Command="{Binding SelectionChangedCommand}"
                CommandParameter="{Binding SelectedItems,
                    ElementName=MyDataGrid}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</sdk:DataGrid>

I slapped a quick sample and published it here (VS2010, SL4 but the concept works in SL3 and WPF too).

Cheers!

Laurent

Be careful when installing the Blend Windows Phone 7 Add-In

There was a small issue today with the release of the Windows Phone Developer Tools CTP (April 2010 Refresh) refresh. The issue is that the Expression Blend Add-in Preview for Windows Phone (April Refresh) is not compatible with Blend 4.0.20408.0, which was the public RC (release candidate).

A few days ago, the Blend team released a fix for an issue that was sometimes causing a crash when Blend was starting up. This new release (V4.0.20421.0) was not very well announced however, and many people (including me) did not install it. After all, Blend did not crash at startup of either of my machines, so I didn’t deem necessary to install yet a new RC.

However, it is now clear that the Windows Phone 7 Add-In needs this latest-and-greatest version to work. If you have Blend 4.0.20408.0, you won’t be able to work with Windows Phone 7 in Blend.

To add to the confusion, the page where you can download V4.0.20421.0 from has an error, and the wrong version number is shown (at least at the time of writing). Do not let this confuse you. You must download this version and install it.

Hopefully this helps clarify some of the confusion…

Happy WinPhone7 coding :)

Laurent

 

Crowdsourcing MVVM Light Toolkit support

Considering the number of emails that are sent to me asking for support for MVVM Light toolkit, I find myself unable to answer all of them in sufficient time to make me feel good.

In consequence, I started to send the following message in response to support queries, either per email or on the MVVM Light Codeplex discussion page.

Hi,

I am doing my best to answer all the questions as fast as possible. I receive a lot of them, however, and cannot reply to everyone fast enough to make me happy.

Due to this, I would like to encourage you to post your question on StackOverflow, and tag it with the tag mvvm-light.

StackOverflow is an awesome site where tons of developers help others with their technical question.

http://stackoverflow.com/questions/tagged/mvvm-light

I will monitor this tag on the StackOverflow website and do my best to answer questions. The advantage of StackOverflow over the Codeplex discussion is the sheer number of qualified developers able to help you with your questions, the visibility of the question itself, and the whole StackOverflow infrastructure (reputation, up- or down-vote, comments, etc)

Thanks!

Laurent

Bug reports

Regarding bug reports, feel free to continue to send them to the Codeplex site (preferred), or to me directly.

I hope that this will help all support queries to be answered faster, and with the great quality for which the StackOverflow users are known!

 

Small change in MVVM Light Toolkit templates for Blend 4 RC

Ah, the joy of new releases… You will find that the MVVM Light Toolkit works fine with Visual Studio 2010 RTM and Blend 4 RC except for a few adjustments:

Blend templates

The path to the Expression Blend 4 project templates changed. If you start Expression Blend 4 RC now, you will likely not see the MVVM Light templates in the New Project dialog.

 20100403003

New Project dialog with MVVM Light

To restore the templates, follow the steps:

  • Open Windows Explorer
  • Navigate to C:\Users\[username]\Documents\Expression (or simply type My Documents in Windows Explorer and then open the Expression folder).
  • Change the name of the “Blend 4 beta” folder into “Blend 4”.

That’s it, you should now see the templates in the New Project dialog in Blend 4.

Note that since the new name is “Blend 4”, I hope that I won’t need to do the same exercise when Blend 4 RTM is released!

Windows Phone 7 templates

Since the Windows Phone 7 tools are not ready yet for Visual Studio 2010 RTM and Blend 4 RC, the templates in the Silverlight for Windows Phone folders will not work. You will get an error if you try to create a new such project in the newly released environment.

I hesitated to remove these templates from the current packages, but honestly that is a lot of trouble for a very short time before the tools for Windows Phone 7 are released (note: I don’t have any information as to when these tools will be released). In the mean time, just don’t create a WinPhone7 application.

Reminder: If you want to write code for Windows Phone 7, you need to keep the Visual Studio 2010 RC as well as Expression Blend 4 beta.

Updated package

I uploaded an update to the Blend 4 templates. It is available like before on the “Install manually” page and on the Codeplex page.

 

Using commands with ApplicationBarMenuItem and ApplicationBarButton in Windows Phone 7

Unfortunately, in the current version of the Windows Phone 7 Silverlight framework, it is not possible to attach any command on the ApplicationBarMenuItem and ApplicationBarButton controls. These two controls appear in the Application Bar, for example with the following markup:

<phoneNavigation:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar x:Name="MainPageApplicationBar">
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem 
                Text="Add City" />
            <shell:ApplicationBarMenuItem 
                Text="Add Country" />
        </shell:ApplicationBar.MenuItems>
        <shell:ApplicationBar.Buttons>
            <shell:ApplicationBarIconButton 
                IconUri="/Resources/appbar.feature.video.rest.png" />
            <shell:ApplicationBarIconButton 
                IconUri="/Resources/appbar.feature.settings.rest.png" />
            <shell:ApplicationBarIconButton 
                IconUri="/Resources/appbar.refresh.rest.png" />
        </shell:ApplicationBar.Buttons>
    </shell:ApplicationBar>
</phoneNavigation:PhoneApplicationPage.ApplicationBar>

This code will create the following UI:


Application bar, collapsed


Application bar, expanded

ApplicationBarItems are not, however, controls. A quick look in MSDN shows the following hierarchy for ApplicationBarMenuItem, for example:

Unfortunately, this prevents all the mechanisms that are normally used to attach a Command (for example a RelayCommand) to a control. For example, the attached behavior present in the class ButtonBaseExtension (from the Silverlight 3 version of the MVVM Light toolkit) can only be attached to a DependencyObject. Similarly, Blend behaviors (such as EventToCommand from the toolkit’s Extras library) needs a FrameworkElement to work.

Using code behind

The alternative is to use code behind. As I said in my MIX10 talk, the MVVM police will not take your family away if you use code behind (this quote was actually suggested to me by Glenn Block); the code behind is there for a reason. In our case, invoking a command in the ViewModel requires the following code:

In MainPage.xaml:

<shell:ApplicationBarMenuItem Text="My Menu 1"
    Click="ApplicationBarMenuItemClick"/>

In MainPage.xaml.cs

private void ApplicationBarMenuItemClick(
    object sender, 
    System.EventArgs e)
{
    var vm = DataContext as MainViewModel;
    if (vm != null)
    {
        vm.MyCommand.Execute(null);
    }
}

Conclusion

Resorting to code behind to bridge the gap between the View and the ViewModel is less elegant than using attached behaviors, either through an attached property or through a Blend behavior. It does, however, work fine. I don’t have any information if future changes in the Windows Phone 7 Application Bar API will make this easier. In the mean time, I would recommend using code behind instead.

 

MVVM Light Toolkit V3 SP1 for Windows Phone 7

20100404001

He he I start to sound like Microsoft… Anyway… I just released a service pack (SP1) for MVVM Light Toolkit V3.

Why?

Well mostly because I worked a bit more with the Windows Phone 7 tools that were released at MIX0, and I noticed a few things that could be better in the Windows Phone 7 template. Also, I only found out at MIX that you can actually install custom project templates for Visual Studio Express. For some reason I thought it was not possible.

The best way to solve these issues is through a service pack, which consists of a few zip files. Simply follow the instructions on the “Installing Manually” page. You can go ahead and overwrite the files that were installed with V3, all the file structure and names are exactly the same.

What?

So what do you get in this service pack that was not already in V3? (for more info about what’s new in V3, check the What’s New page).

  • Project and Item templates for Visual Studio 10 Express (phone edition). Unzip these files in your “My Documents” folder, and you can now create a new MVVM Light application in the WinPhone7 version of Visual Studio 2010 Express.
  • Signed assemblies: All the assemblies are now signed, which is a requirement in certain build configurations.
  • XML documentation files: Thanks to Matt Casto for pinging me and reminding me that I had forgotten to include them (doh).
  • New and improved Windows Phone 7 assemblies and templates: This one deserves its own section (see below).

What was wrong with the old Silverlight 3 assemblies in Windows Phone 7 projects?

It was kind of weird. Functionality wise, it was working just right. However, if you noticed, the EventToCommand behavior was not visible in the Assets tab of Expression Blend, under Behaviors, where it should normally have been.

The reason was that even though the Windows Phone 7 is using Silverlight 3, the System.Windows.Interactivity that Blend was expecting is the version that is normally used in Silverlight 4. Yeah, I know, it’s weird.

This led me to create a specific version of these assemblies for the phone. The assemblies are located into C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Binaries\WP7. There are 3 DLLs:

  • GalaSoft.MvvmLight.WP7.dll with RelayCommand, Messenger and ViewModelBase
  • GalaSoft.MvvmLight.Extras.WP7.dll with EventToCommand and DispatcherHelper
  • System.Windows.Interactivity.dll which is the same DLL installed in the Blend SDK, and which is needed for the EventToCommand behavior to work.

Happy coding!

That’s all! Download and install the service pack according to the instructions on the Installation page, and create your first MVVM Light application for the phone (a blog post will follow later with more details).

 

Sample code and slides for my TechDays10 (Belgium) talks

The source code for my MVVM talk titled “Understanding the MVVM Pattern” given at TechDays 2010 in Antwerpen, Belgium, is available online. It is actually the same code than the MIX10 one, but I added the Windows Phone 7 MVVM Light application (available in the folder titled “Mix10.MvvmDemo2-End”.

Note: before unpacking the zip file, you should right click on it, and select properties / Unblock.

I also published the slides for my two talks:

As far as I know, the videos will be online soon, stay tuned and I will announce when it is the case.

Get Started page for the MVVM Light Toolkit: http://www.galasoft.ch/mvvm/getstarted