【问题标题】:shared views between two WPF apps using MVVM light使用 MVVM light 在两个 WPF 应用程序之间共享视图
【发布时间】:2011-12-24 14:00:33
【问题描述】:

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

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

Views 库有一个 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”

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

【问题讨论】:

    标签: wpf xaml data-binding mvvm mvvm-light


    【解决方案1】:

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

    【讨论】:

    • 好的 - 但我无法解析我的静态资源“定位器”。在 App.xaml(在常规 WPF 客户端中)它工作正常,但在 Views 类库项目中,使用我的 ResourceDictionary.xaml,我无法解决它。有什么我错过的技巧吗?
    • @kindohm 您的项目是否仍然运行?我经常收到有关无法解决的 StaticResources 的 XAML 错误,然后就忽略它们。
    • 不,它没有。我收到一个运行时错误:{“找不到名为 'Locator' 的资源。资源名称区分大小写。”} 我的 ResourceDictionary.xaml 设置为“页面”构建操作。为了清楚起见,我在我的 WPF 客户端中定义了一个没有资源的 App.xaml,在我的 Views 库中定义了一个 ResourceDictionary.xaml。 Views 库中的视图无法解析 ResourceDictionary.xaml 中定义的 Locator
    • @kindohm 你的Locator 是静态类吗?我见过的大部分ViewModelLocators都是静态的,然后你可以绑定Source={x:Static local:MyViewModelLocator}
    • 次要细节,但在这里澄清一下 - 静态源必须指向类型的属性,而不是类型本身,因此 Source={x:Static local:Locator.Instance}。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2021-04-12
    • 2018-04-19
    • 2010-11-17
    • 2011-12-15
    • 2012-02-11
    相关资源
    最近更新 更多