Quick tip: Adding objects in resources

.NET, Build, MVVM, Technical stuff, Windows 8, Work
See comments

If you are using MVVM-Light style ViewModel creation (often referred to as “view-first”), you might have noticed that you cannot build if you have an object in the view’s resources. It means that the code below does not compile.

    <vm:MyViewModel x:Key="MyViewModel"
                    xmlns:vm="using:Application1.ViewModel" />

    <Binding Source="{StaticResource MyViewModel}" />

I was told it is a bug that is being fixed, so no worries, the view-first way will still work! As a workaround, you can create the ViewModel in code behind and then save it into the resources, or simply assign it to the DataContext.

partial class MainPage
    public MainPage()
        DataContext = new MyViewModel();

Of course this way is less blendable (meaning that Expression Blend will not be able to create the ViewModel and to show design time data if available. However, since we don’t have Expression Blend for XAML yet, it’s not that big a deal. Let’s hope that these small issues will be resolved soon.

Previous entry | Next blog entry

Comments for Quick tip: Adding objects in resources