如何使用 Prism 在 Xamarin.Forms 中自动注册视图
How to register views automatically in Xamarin.Forms with Prism
在使用 Prism 和 Unity 的 Xamarin.Forms 中,有没有一种方法可以在不显式指定的情况下注册所有受导航影响的视图?
Prism 提供的示例项目在 App.xaml.cs 中有一个函数 RegisterTypes,其中包含以下行:
Container.RegisterTypeForNavigation<MainPage>();
我希望在开发应用程序的某个时候它会更大。
我不是 Unity 专家,但我尝试了 DependencyService 或 IUnityContainer 的一些方法,但没有成功。
Container.Registrations.Where(cm => cm.RegisteredType == typeof (IView));
Container.ResolveAll<IView>();
DependencyService.Get<IEnumerable<IView>>();
那么我将如何注册所有视图(或者至少是视图的一个子集,例如,实现给定界面的视图)以进行导航?
只需一点反射,您就可以注册从 Page
.
继承的所有类型的核心程序集
public class Bootstrapper : UnityBootstrapper
{
protected override void OnInitialized()
{
NavigationService.Navigate("MainPage");
}
protected override void RegisterTypes()
{
RegisterAllPages();
}
private void RegisterAllPages()
{
var pageBaseTypeInfo = typeof(Page).GetTypeInfo();
var types = GetType().GetTypeInfo().Assembly.DefinedTypes;
var pageTypeInfos = types
.Where(x => x.IsClass && pageBaseTypeInfo.IsAssignableFrom(x));
foreach (var page in pageTypeInfos)
{
// the next two lines do what RegisterTypeForNavigation does
Container.RegisterType(typeof(object), page.AsType(), page.Name);
PageNavigationRegistry.Register(page.Name, page.AsType());
}
}
}
在使用 Prism 和 Unity 的 Xamarin.Forms 中,有没有一种方法可以在不显式指定的情况下注册所有受导航影响的视图?
Prism 提供的示例项目在 App.xaml.cs 中有一个函数 RegisterTypes,其中包含以下行:
Container.RegisterTypeForNavigation<MainPage>();
我希望在开发应用程序的某个时候它会更大。
我不是 Unity 专家,但我尝试了 DependencyService 或 IUnityContainer 的一些方法,但没有成功。
Container.Registrations.Where(cm => cm.RegisteredType == typeof (IView));
Container.ResolveAll<IView>();
DependencyService.Get<IEnumerable<IView>>();
那么我将如何注册所有视图(或者至少是视图的一个子集,例如,实现给定界面的视图)以进行导航?
只需一点反射,您就可以注册从 Page
.
public class Bootstrapper : UnityBootstrapper
{
protected override void OnInitialized()
{
NavigationService.Navigate("MainPage");
}
protected override void RegisterTypes()
{
RegisterAllPages();
}
private void RegisterAllPages()
{
var pageBaseTypeInfo = typeof(Page).GetTypeInfo();
var types = GetType().GetTypeInfo().Assembly.DefinedTypes;
var pageTypeInfos = types
.Where(x => x.IsClass && pageBaseTypeInfo.IsAssignableFrom(x));
foreach (var page in pageTypeInfos)
{
// the next two lines do what RegisterTypeForNavigation does
Container.RegisterType(typeof(object), page.AsType(), page.Name);
PageNavigationRegistry.Register(page.Name, page.AsType());
}
}
}