0 .net c# wpf prism windows-store-apps
我正在研究windows store app中的棱镜.我遇到了问题.我有很多观点,我想将它们分成不同的文件夹.但问题是NavigationService无法找到它们.说明书说所有的视图显示放入views文件夹,然后导航服务可以使用navigationservice.navigate("main",null)导航到它们,但是如果视图不在导航服务找不到它们的views文件夹的根目录中
NavigationService根据约定查找Views和ViewModels.所有视图必须位于"视图"文件夹中,ViewModel必须位于"ViewModels"文件夹中.如果id不适合您,可以执行以下操作:
将以下类添加到项目中:
public class ViewViewModelTypeResolver
{
private const string ViewNameSuffix = "Page"; // You can change this View name suffix
private const string ViewModelNameSuffix = "ViewModel"; // You can change this ViewModel name suffix
private readonly Lazy<Dictionary<string, Type>> _uiAssemblyExportedTypes;
private Dictionary<string, Type> UiAssemblyExportedTypes
{
get { return _uiAssemblyExportedTypes.Value; }
}
public ViewViewModelTypeResolver(Type typeFromUiAssembly)
{
_uiAssemblyExportedTypes = new Lazy<Dictionary<string, Type>>(() => GetUiAssemblyExportedTypes(typeFromUiAssembly));
}
public Type GetViewType(string viewTypeName)
{
return UiAssemblyExportedTypes[viewTypeName];
}
public Type GetViewModelType(Type viewType)
{
var pageNameWithoutSuffix = viewType.Name.Remove(viewType.Name.LastIndexOf(ViewNameSuffix, StringComparison.Ordinal));
var viewModelName = String.Concat(pageNameWithoutSuffix, ViewModelNameSuffix);
return UiAssemblyExportedTypes[viewModelName];
}
private static Dictionary<string, Type> GetUiAssemblyExportedTypes(Type typeFromUiAssembly)
{
return typeFromUiAssembly.GetTypeInfo().Assembly.ExportedTypes.ToDictionary(type => type.Name, type => type, StringComparer.Ordinal);
}
}
Run Code Online (Sandbox Code Playgroud)将ViewViewModelTypeResolver添加到App构造函数:
public App()
{
var mainPage = typeof(MainPage); // Any of pages from your solution. Pay attention that the resolver will be able to resolve Views and ViewModels that locates in the same project as specified page.
_viewViewModelTypeResolver = new ViewViewModelTypeResolver(mainPage);
}
Run Code Online (Sandbox Code Playgroud)当你使用Prism时,我假设你继承了你的App类MvvmAppBase.如果是这样,你应该覆盖GetPageType方法:
protected override Type GetPageType(string pageToken)
{
return _viewViewModelTypeResolver.GetViewType(pageToken);
}
Run Code Online (Sandbox Code Playgroud)然后添加SetDefaultViewTypeToViewModelTypeResolver在OnInitializeAsync方法:
protected override async Task OnInitializeAsync(IActivatedEventArgs args)
{
// Your initialization code
ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(GetViewModelType);
// Your initialization code
}
private Type GetViewModelType(Type pageType)
{
return _viewViewModelTypeResolver.GetViewModelType(pageType);
}
Run Code Online (Sandbox Code Playgroud)现在,您可以导航到任何页面,即使它们被分成不同的文件夹.
| 归档时间: |
|
| 查看次数: |
404 次 |
| 最近记录: |