【问题标题】:WPF UserControl using MVVMLight can't find ViewModelLocator使用 MVVMLight 的 WPF UserControl 找不到 ViewModelLocator
【发布时间】:2018-05-30 21:16:01
【问题描述】:

我有两个问题。我有一个 WPF UserControl,它是另一个 WPF 应用程序的 .dll 插件。

首先,除非我在使用我的 Usercontrol dll 的 WPF 应用程序中安装 MVVMLight,否则它会抱怨找不到任何 MVVMLight 库。无论如何我不必使用我的 UserControl dll 在主 WPF 应用程序上安装 MVVMLight 吗?

其次,在我的UserControl中找不到ViewModelLocator。我尝试将其设为我的 UserControl 的 StaticResource,但找不到 ViewModelLocator。

请帮忙。

【问题讨论】:

  • 显然你的 UserControl 依赖于 MvvmLight。您要么必须删除此依赖项,要么确保始终将 MvvmLight 程序集引入任何使用您的 UserControl 的应用程序中。
  • 所以没有办法将它们捆绑到我的 DLL 中?另外,关于它为什么找不到我的 ViewModelLocator 的任何想法?

标签: c# wpf user-controls mvvm-light viewmodellocator


【解决方案1】:

这是一个如何使用视图模型定位器的示例:

从简单的ViewModel开始:

public class MainViewModel
{
    public string TestProperty { get; set; } = "ViewModelLocator works fine!";
}

定义ViewModelLocator

public class ViewModelLocator
{
    private static readonly MainViewModel mainViewModel;

    static ViewModelLocator()
    {
        mainViewModel = new MainViewModel();
    }

    public static MainViewModel MainViewModel => mainViewModel;
}

如您所见,您的 ViewModel 的实例仅在静态构造函数中创建一次,然后返回相同的实例。

这里是View

<Window x:Class="SetViewModelLocator.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SetViewModelLocator"
    xmlns:vm="clr-namespace:SetViewModelLocator.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <vm:ViewModelLocator x:Key="ViewModelLocator"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=MainViewModel}">
    <TextBlock Text="{Binding TestProperty}"/>
</Grid>

将定位器设置为Resource,并将其用作主容器的DataContext,在本例中为Grid

【讨论】:

  • 这不能回答我的问题。我需要它位于 DLL 中的 UserControl 中,然后在另一个 WPF 项目中使用它,我无法修改 app.xaml 以将定位器放入。我的问题是在 UserControl 中找不到我的定位器。
猜你喜欢
  • 1970-01-01
  • 2015-07-08
  • 2015-08-28
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
  • 2022-01-06
  • 2012-12-31
  • 1970-01-01
相关资源
最近更新 更多