我正在尝试通过将ViewModelLocator声明为App.xaml中的资源来使用它。它是一个非常简单的类,如下所示:
public class ViewModelLocator
{
public ShellViewModel ShellPage
{
get
{
return new ShellViewModel();
}
}
}
App.xaml文件如下:
<Application x:Class="SomeNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SomeNamespace.ViewModels">
<Application.Resources>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
</Application>
App.xaml.cs如下:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var view = new ShellView();
Current.MainWindow = view;
Current.MainWindow.Show();
}
}
ShellView.xaml是下面的内容:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SomeNamespace.ShellView"
Title="MainWindow"
Height="350"
Width="525"
ResizeMode="NoResize"
MinWidth="700"
MinHeight="700"
DataContext="{Binding ShellPage, Source={StaticResource ViewModelLocator}}"
>
<Grid>
<TextBlock Text="{Binding Title}"></TextBlock>
</Grid>
</Window>
我可以在Visual Studio设计器中看到正确的标题,但是当我运行应用程序时,得到XamlParseException:
“在'System.Windows.StaticResourceExtension'上提供值”引发了异常。行号“11”和行位置“9”。
内部异常具有 {“找不到名为'ViewModelLocator'的资源。资源名称区分大小写。”}
我想念什么吗?
最佳答案
尝试将其放在ResourceDictionary中
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
</ResourceDictionary>
</Application.Resources>
编辑:
我通过在应用程序中使用Startup事件解决了问题,而不是覆盖OnStartup。
<Application x:Class="TestWPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TestWPF.ViewModels"
Startup="App_Startup">
<Application.Resources>
<vm:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>
</Application>
代码
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
var view = new ShellView();
Current.MainWindow = view;
Current.MainWindow.Show();
}
}
关于wpf - 找不到名为 'ViewModelLocator'的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19011463/