我想自己实现 ViewModelLocator 。所以我实现了世界上最简单的应用程序。我在 this 教程中做了所有事情。但我仍然得到一个异常(exception):



这是这一行:

DataContext="{Binding MainWindowViewModel, Source={StaticResource ViewModelLocator}}">

这是代码:

App.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>

App.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(); }
        }
    }
}

MainWindow.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";
        }
    }
}

this answer 我发现:



所以我在 App.xaml 中有它。如果有人能解释一下这里发生了什么?为什么我收到这个错误?

最佳答案

您遇到了这个错误 WPF - App.xaml file does not get parsed if my app does not set a StartupUri?

从该页面:



从该页面开始,有 3 个解决方案(为了完整性在此处进行总结):

  • 添加x:Name="App"
  • 在 App.xaml 中添加更多资源,如 <viewModelLocatorDemo:ViewModelLocator x:Key="ViewModelLocator"/><viewModelLocatorDemo:ViewModelLocator x:Key="ViewModelLocator2"/>
  • 与其覆盖 OnStartup,不如尝试使用事件,Startup="Application_Startup"

  • 这绝对不是显而易见的,并且很难排除故障,甚至在我自己的搜索中也很难找到答案。希望这个答案能帮助其他人找到另一个答案。

    关于c# - 实现自己的 ViewModelLocator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35006559/

    10-11 19:29
    查看更多