我想自己实现 ViewModelLocator。所以我实现了世界上最简单的应用程序。我按照本教程进行了所有操作。但我仍然遇到一个例外:
发生 XamlParseException
抛出异常:PresentationFramework.dll 中的“System.Windows.Markup.XamlParseException”
附加信息:“在 'System.Windows.StaticResourceExtension' 上提供值引发异常。” 行号“8”和行位置“9”。
这是这一行:
DataContext="{Binding MainWindowViewModel, Source={StaticResource ViewModelLocator}}">
这是代码:
应用程序.xaml
<Application x:Class="ViewModelLocatorDemo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModelLocatorDemo="clr-namespace:ViewModelLocatorDemo">
<Application.Resources>
<viewModelLocatorDemo:ViewModelLocator x:Key="ViewModelLocator"/>
</Application.Resources>
</Application>
应用程序.xaml.cs
namespace ViewModelLocatorDemo
{
using System.Windows;
using ViewModelLocatorDemo.Views;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
}
}
ViewModelLocator.cs
namespace ViewModelLocatorDemo
{
using ViewModels;
public class ViewModelLocator
{
public MainWindowViewModel MainWindowViewModel
{
get { return new MainWindowViewModel(); }
}
}
}
主窗口.xaml
<Window x:Class="ViewModelLocatorDemo.Views.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"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300"
DataContext="{Binding MainWindowViewModel, Source={StaticResource ViewModelLocator}}">
<Grid>
<Frame x:Name="MainFrame" Margin="50" BorderThickness="2" BorderBrush="Black" />
</Grid>
</Window>
MainWindowViewModel.cs
namespace ViewModelLocatorDemo.ViewModels
{
public class MainWindowViewModel
{
public string MainText { get; set; }
public MainWindowViewModel()
{
MainText = "The first page";
}
}
}
在这个答案中,我发现:
确保在使用之前定义资源(按 Xaml 解析顺序)。最简单的方法是将其放入 App.xaml
所以我在 App.xaml 中有它。如果有人能解释一下这里发生了什么?为什么我会收到此错误?