1
votes

Using MVVM Light, I have two WPF applications that reference a common Views library. I also have a ViewModels library. The ViewModels library has a ViewModelLocator.

The dependencies are pretty simple: WPF apps -> Views -> ViewModels

The Views library has a ResourceDictionary and defines a ViewModelLocator resource for data binding at runtime and design time:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:ViewModels;assembly=ViewModels">
    <vm:ViewModelLocator x:Key="Locator"/>
</ResourceDictionary>

The problem is that when I go to set the DataContext at the top level element of my Views, I get an exception:

<UserControl x:Class="Views.WelcomeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             DataContext="{Binding WelcomeViewModel, Source={DynamicResource Locator}}">
    <Grid>
        <TextBlock Text="{Binding Text}"/>
    </Grid>
</UserControl>

Exception: A 'DynamicResourceExtension' cannot be set on the 'Source' property of type 'Binding'. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject

What am I doing wrong? Is defining the Locator in the Views as a resource even the best approach?

1

1 Answers

3
votes

You cannot useSource={DynamicResource Locator} in your binding. If you use the Source property, you need to use a StaticResource