【问题标题】:WPF Can't find local resource when executedWPF执行时找不到本地资源
【发布时间】:2017-08-03 10:16:08
【问题描述】:

我在我的应用程序中定义了一个应用程序资源,它存储了我的 ViewModels 和一个导航元素来导航页面。这在 Visual Studio 的 xaml 编辑器中运行良好,因为所有数据绑定都在那里工作。但是,当我尝试在调试器中运行应用程序时,它会抛出一个异常,并显示消息 Cannot find source with the name ViewModelLocator. 有人知道出了什么问题吗?

我在我的 App.xaml 中定义了一个本地资源,如下所示:

<Application.Resources>
    <viewmodel:ViewModelLocator x:Key="ViewModelLocator"/>
</Application.Resources>

我尝试这样使用:

<Page x:Class="QardPrint.PageEmployeesList"
  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" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:QardPrint"
  xmlns:viewmodel="clr-namespace:QardPrint.ViewModel"
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="300"
  Title="PageEmployeesList"
  DataContext="{Binding EmployeesListViewModel, Source={StaticResource ViewModelLocator}}">

我的 ViewModelLocator 类看起来像这样

public class ViewModelLocator
{
    public EmployeesListViewModel EmployeesListViewModel => new EmployeesListViewModel(App.Navigation);
}

【问题讨论】:

  • ViewModelLocatorApp.xaml 是否在同一个程序集中?
  • 是的,它们都在同一个程序集中。它们在不同的命名空间中,但我也尝试将它们放在同一个命名空间中,但仍然弹出异常。

标签: c# .net wpf xaml mvvm


【解决方案1】:

尝试使用ResourceDictionary:

App.xaml:

<Application xmlns:viewmodel="clr-namespace:QardPrint.ViewModel">
    <Application.Resources>
        <ResourceDictionary>
            <viewmodel:ViewModelLocator x:Key="Locator" />

QardPrint.PageEmployeesLis.Xaml:

<Page x:Class="QardPrint.PageEmployeesList"
  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" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:QardPrint"
  xmlns:viewmodel="clr-namespace:QardPrint.ViewModel"
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="300"
  Title="PageEmployeesList"
  DataContext="{Binding EmployeesListViewModel, Source={StaticResource Locator}}">

【讨论】:

  • 感谢您的回复。不幸的是,我得到了同样的错误。
  • 您是否尝试过清理并重建解决方案?
  • 清理和重建没有帮助。我将最少的代码转移到一个新项目中,这似乎有效。将逐步移动更多代码以查看问题发生在哪里。
【解决方案2】:

我发现了问题。我在 App.xaml 中删除了启动参数。再次添加后问题就解决了。 我这样做是因为我在 app.cs 的启动功能中制作了另一个窗口。但这可能是一个糟糕的设计,所以要弄清楚如何做得更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2013-11-04
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多