UWP Prism ViewModel является нулевым - PullRequest
0 голосов
/ 14 ноября 2018

Использование универсальных шаблонов Windows для Visual Studio 2017. Я создал тестовое приложение UWP с использованием Prism.Все работает нормально, пока я не добавлю новую пустую страницу в приложение.Представление называется:

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

нулевой?Как мне отладить это?

Ответы [ 2 ]

0 голосов
/ 15 ноября 2018

Я допустил ошибку с соглашениями об именах. Если ваша страница AbcPage, тогда viewmodel должен быть AbcViewModel, а не AbcPageViewModel.

0 голосов
/ 15 ноября 2018

Для использования ранних выпусков призмы в uwp вам необходимо настроить дополнительную базу данных для собственного проекта uwp, например, App class и Page class. Конечно, чиновник предоставил пример кода , на который вы могли бы сослаться.

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, которая не выпускает, новый режим использования. Для более подробной информации, пожалуйста, проверьте ссылку .

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));
    }
}
...