2017-08-03 47 views
2

我在我的应用程序中定义了一个应用程序资源,它将我的ViewModel与导航元素一起存储以导航页面。这在Visual Studio的xaml编辑器中工作良好,因为所有数据绑定都在那里工作。但是,当我尝试在调试器中运行应用程序时,它会显示一条消息Cannot find source with the name ViewModelLocator.的异常有人知道发生了什么问题吗?WPF在执行时找不到本地资源

我在我的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); 
} 
+0

“ViewModelLocator”和“App.xaml”是否在同一个程序集中? –

+0

是的,他们都在同一个大会。它们位于不同的命名空间中,但我也尝试将它们放在相同的命名空间中,并且Exception仍然弹出。 –

回答

0

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

0

尝试使用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}}"> 
+0

感谢您的回复。不幸的是我得到了同样的错误。 –

+0

您是否尝试清理解决方案并重建它? –

+0

尝试使用从此使用的解决方案:https://stackoverflow.com/a/19012976/4772806 –