背景:我正在使用MVVM创建一个WPF应用程序,并使用DI容器来构建我的ViewModel
我的App.xaml看起来像这样:
<Application x:Class="WpfApp.App"
...xmlns etc...
StartupUri="MainWindow.xaml">
<Application.Resources>
<app:ServiceLocator x:Key="serviceLocator" />
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml看起来像这样:
<Window x:Class="CompositeMefWpfApp.MainWindow"
...xmlns etc... >
<Control.DataContext>
<Binding Path="MainWindowViewModel" Source="{StaticResource serviceLocator}" />
</Control.DataContext>
Run Code Online (Sandbox Code Playgroud)
现在,这一切都运行正常,但是StartupUri硬编码到XAML中,我不想要.
根据我发现的几篇博文和文章的指导,我删除了StartupUri,并尝试MainWindow通过挂钩OnStartup在App.xaml.cs中创建,如下所示:
protected override void OnStartup( StartupEventArgs e )
{
base.OnStartup(e);
new MainWindow().Show();
}
Run Code Online (Sandbox Code Playgroud)
问题是,在尝试显示窗口时应用程序崩溃,但有以下异常:
找不到名为"{serviceLocator}"的资源.资源名称区分大小写.标记文件'WpfApp; component/mainwindow.xaml'中对象'System.Windows.Data.Binding'出错'第8行第45位.
据我所知,该<Application.Resources>部分根本没有从xaml文件中读出.我可以在OnStartup中添加一些代码来以编程方式添加资源,如下所示:
Resources.BeginInit();
Resources.Add("serviceLocator", new ServiceLocator());
Resources.EndInit();
Run Code Online (Sandbox Code Playgroud)
然而,这是一个丑陋的黑客,如果我想稍后在app.xaml文件中添加其他东西,并没有帮助我:-(
我应该挂钩其他一些活动吗?有没有解决的办法?
在XAML我试图使用的页面内IValueConverter,它会抛出一个错误.
IValueConverter是在另一组件中,我已经添加了一个参考在我的页面顶部,我有这个:
xmlns:converters="clr-namespace:Converters;assembly=Converters"
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/DialogStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<converters:NoWhiteSpaceConverter x:Key="NoWhiteSpaceConverter" />
</ResourceDictionary>
</Page.Resources>
Run Code Online (Sandbox Code Playgroud)
然后我尝试稍后使用它:
<TextBox Text="{Binding SomeText, Converter={StaticResource NoWhiteSpaceConverter}}" />
Run Code Online (Sandbox Code Playgroud)
任何人都可以看到问题是什么?