使用MVVM light在两个WPF应用程序之间共享视图

使用MVVM light在两个WPF应用程序之间共享视图,wpf,xaml,data-binding,mvvm,mvvm-light,Wpf,Xaml,Data Binding,Mvvm,Mvvm Light,使用MVVM Light,我有两个引用公共视图库的WPF应用程序。我还有一个ViewModels库。ViewModels库具有ViewModelLocator 依赖关系非常简单: WPF应用程序->视图->视图模型 视图库有一个ResourceDictionary,并为运行时和设计时的数据绑定定义了ViewModelLocator资源: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/

使用MVVM Light,我有两个引用公共视图库的WPF应用程序。我还有一个ViewModels库。ViewModels库具有ViewModelLocator

依赖关系非常简单: WPF应用程序->视图->视图模型

视图库有一个ResourceDictionary,并为运行时和设计时的数据绑定定义了ViewModelLocator资源:

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

问题是,当我在视图的顶层元素设置DataContext时,会出现一个异常:

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

例外情况: 无法在“Binding”类型的“Source”属性上设置“DynamicResourceExtension”。只能对DependencyObject的DependencyProperty设置“DynamicResourceExtension”


我做错了什么?将视图中的定位器定义为资源是最好的方法吗?

您不能在绑定中使用
Source={DynamicResource Locator}
。如果使用
Source
属性,则需要使用
StaticResource

确定-但我无法解析静态资源“定位器”。在App.xaml中(在常规WPF客户端中),它可以正常工作,但在Views类库项目中,使用我的ResourceDictionary.xaml,我无法解析它。我错过了什么把戏吗?@kindohm你的项目运行正常吗?我经常收到关于静态资源的XAML错误,这些错误无法得到解决,我只是忽略它们。不,它不会。我得到一个运行时错误:{“找不到名为“Locator”的资源。资源名称区分大小写。}My ResourceDictionary.xaml被设置为“Page”生成操作。需要明确的是,我在WPF客户机中定义了一个App.xaml,没有任何资源,在我的视图库中定义了一个ResourceDictionary.xaml。视图库中的视图无法解析ResourceDictionary中定义的定位器。xaml@kindohm您的
定位器是静态类吗?我看到的大多数
ViewModelLocator
都是静态的,然后您可以绑定
Source={x:static local:MyViewModelLocator}
次要细节,但这里需要澄清的是-静态源必须指向类型上的属性,而不是类型本身,因此Source={x:static local:Locator.Instance}。谢谢你的帮助!