首页 > 解决方案 > 是否可以在 App.xaml.cs 上自动注册 ViewModels 和 Views

问题描述

OnStartUp是否可以在没有像 Prism 这样的类库的情况下使用视图自动注册视图模型App.xaml.cs

我以前在应用程序启动时的 Prism Xamarin 项目中有类似的东西。

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    //Registered Navigation Containers
    containerRegistry.RegisterForNavigation<LoginPage>("Login");
    containerRegistry.RegisterForNavigation<RegisterPage>("Register");
    containerRegistry.RegisterForNavigation<ProfilePage>("Profile");
    containerRegistry.RegisterForNavigation<CreateAppointmentPage>("CreateAppointment");
    containerRegistry.RegisterForNavigation<NotificationPage>("Notification");
    //Dependency Services
    containerRegistry.RegisterSingleton<IConnectivityService, ConnectivityService>();
    containerRegistry.RegisterSingleton<IAuthenticationService, AuthenticationService>();
    containerRegistry.RegisterSingleton<IAppAPIService, AppAPIService>();
    containerRegistry.RegisterSingleton<IPushNotificationManager, PushNotificationManager>();
}

我现在的公司希望避免使用库。我的目标是为所有视图提供一个干净的代码隐藏。我想避免在我的代码隐藏中出现类似的东西:

public MainWindow()
{
     InitializeComponent();
     DataContext = new MainWindowViewModel();
}

我希望我的问题很清楚。谢谢你。

标签: c#.netwpf.net-coremvvm

解决方案


网络框架内没有什么是自动的。

您可以先使用视图模型和数据模板来缓解该问题。这就是我通常在单个窗口应用程序中工作的方式。

我在 app.xaml 中有一个资源字典合并,它按类型将用户控件与视图模型相关联。

您可以在这里看到一个非常基本的版本:

https://social.technet.microsoft.com/wiki/contents/articles/52485.wpf-tips-and-tricks-using-contentcontrol-instead-of-frame-and-page-for-navigation.aspx

<DataTemplate DataType="{x:Type local:LoginViewModel}">
    <local:LoginView/>
</DataTemplate>

导航是通过将 mainwindowviewmodel 中的 CurrentView 属性设置为视图模型的实例来完成的。这与 MainWindow 中的内容控件的内容绑定。然后数据模板将模板出适当的用户控件。

需要单例的导航服务和视图模型不能缓存在对象主窗口视图模型实例中。

然后,您“仅”拥有主窗口视图模型。手动实例化 mainwindowviewmodel 有一些优点。这样您就可以控制何时发生昂贵的实例化。这并不是全部自动完成的,因为视图模型需要通过它的 ctor 提供许多服务。

您可以在其中使用任何您喜欢的 DI 来解决依赖关系,同时实例化各种视图模型。或者只是一个带有惰性单例的中介模式提供缓存在自身内部的实例。

你当然可以写点东西。

问题是您可能会重新编写与其他人已经编写的代码非常相似的代码。但是由于您可能没有留出 6 个月的时间来进行框架更换工作,因此您的版本可能会更简单。

Caliburn micro 使用命名约定来关联视图模型和视图。你可以写一些类似的东西并使用反射。

或者,也许你可以回到你的老板那里,讨论他的问题是什么。就个人而言,由于它的复杂性,我不是 Prism 的粉丝。也许这就是他遇到的问题。也许像 mvvmlight 这样更简单的框架会更容易接受。


推荐阅读