使用Visual Studio 2017通用Windows模板,我使用Prism创建了一个测试UWP App。一切正常,直到我向应用程序添加了新的空白页。该视图称为:
AbcPage
XAML
<Page
x:Class="UI_Test_1.Views.AbcPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:UI_Test_1.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prismMvvm="using:Prism.Windows.Mvvm"
prismMvvm:ViewModelLocator.AutoWireViewModel="True"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Grid>
<Button Click="Button_Click" Content="test" />
</Grid>
我添加了
xmlns:prismMvvm="using:Prism.Windows.Mvvm"
prismMvvm:ViewModelLocator.AutoWireViewModel="True"
因此,后面的代码是:
namespace UI_Test_1.Views
{
public sealed partial class AbcPage : Page
{
AbcPageViewModel viewModel => DataContext as AbcPageViewModel;
public AbcPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var vm = viewModel;//this is null
}
}
}
最后是我的ViewModel:
namespace UI_Test_1.ViewModels
{
public class AbcPageViewModel : ViewModelBase
{
public AbcPageViewModel()
{
//never called
}
}
}
这些约定似乎是正确的,还是我弄错了?为什么
AbcViewModel
可以吗?我该如何调试?
答案 0 :(得分:1)
要在uwp中使用棱镜早期版本,您需要基于本地uwp项目(例如App
类和Page
类)进行更多配置。当然,该官员提供了您可以参考的code sample。
public sealed partial class App : PrismUnityApplication
{
public App()
{
InitializeComponent();
}
protected override UIElement CreateShell(Frame rootFrame)
{
var shell = Container.Resolve<AppShell>();
shell.SetContentFrame(rootFrame);
return shell;
}
protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));
return base.OnInitializeAsync(args);
}
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
NavigationService.Navigate(PageTokens.Main.ToString(), null);
return Task.FromResult(true);
}
}
对于未发布的最新7.2版本,具有新的使用模式。有关更多信息,请检查此link。
sealed partial class App : PrismApplication
{
public static IPlatformNavigationService NavigationService { get; private set; }
public App()
{
InitializeComponent();
}
public override void RegisterTypes(IContainerRegistry container)
{
container.RegisterForNavigation<MainPage, MainPageViewModel>(nameof(Views.MainPage));
}
public override void OnInitialized()
{
NavigationService = Prism.Navigation.NavigationService
.Create(new Frame(), Gestures.Back, Gestures.Forward, Gestures.Refresh);
NavigationService.SetAsWindowContent(Window.Current, true);
}
public override void OnStart(StartArgs args)
{
NavigationService.NavigateAsync(nameof(Views.MainPage));
}
}
答案 1 :(得分:1)
我在命名约定上犯了一个错误。如果您的页面是AbcPage,则视图模型应该是AbcViewModel而不是AbcPageViewModel。