c# - 是否可以在 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();
}
我希望我的问题很清楚。谢谢你。
解决方案
网络框架内没有什么是自动的。
您可以先使用视图模型和数据模板来缓解该问题。这就是我通常在单个窗口应用程序中工作的方式。
我在 app.xaml 中有一个资源字典合并,它按类型将用户控件与视图模型相关联。
您可以在这里看到一个非常基本的版本:
<DataTemplate DataType="{x:Type local:LoginViewModel}">
<local:LoginView/>
</DataTemplate>
导航是通过将 mainwindowviewmodel 中的 CurrentView 属性设置为视图模型的实例来完成的。这与 MainWindow 中的内容控件的内容绑定。然后数据模板将模板出适当的用户控件。
需要单例的导航服务和视图模型不能缓存在对象主窗口视图模型实例中。
然后,您“仅”拥有主窗口视图模型。手动实例化 mainwindowviewmodel 有一些优点。这样您就可以控制何时发生昂贵的实例化。这并不是全部自动完成的,因为视图模型需要通过它的 ctor 提供许多服务。
您可以在其中使用任何您喜欢的 DI 来解决依赖关系,同时实例化各种视图模型。或者只是一个带有惰性单例的中介模式提供缓存在自身内部的实例。
你当然可以写点东西。
问题是您可能会重新编写与其他人已经编写的代码非常相似的代码。但是由于您可能没有留出 6 个月的时间来进行框架更换工作,因此您的版本可能会更简单。
Caliburn micro 使用命名约定来关联视图模型和视图。你可以写一些类似的东西并使用反射。
或者,也许你可以回到你的老板那里,讨论他的问题是什么。就个人而言,由于它的复杂性,我不是 Prism 的粉丝。也许这就是他遇到的问题。也许像 mvvmlight 这样更简单的框架会更容易接受。
推荐阅读
- python - 我们可以只命名数据框的前 3 列吗?
- sql - 如何根据别名检查字段是否为空
- git - git ls-remote --tags:如何获取日期信息?
- java - 如何为 SQL Server 构建 Google Cloud SQL JDBC URL
- r - 在 Moran.I 和 moran.test 之间获得不同的测试结果
- tensorflow - 形状与 vgg16 keras 不匹配:预期 ndim=4,发现 ndim=2,收到形状 [无,无]
- c# - 增量(x++)的打印结果返回原始值而不是递增一
- python - Square 客户端 sdk 在使用 list_customers 时返回 KeyError:''
- vue.js - 自动完成输入 Vuetify 错误
- python - 我们如何计算 Python 中所有列中 NOT NULL 值的总数?