情况:我有这些物品:
MainMenuView
MainMenuViewModel
MainMenuPage
MainMenuPage
包含,MainMenuView
如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:xxx_App.Pages"
xmlns:views="clr-namespace:xxx_App.Views"
x:Class="xxx_App.Pages.MainMenuPage">
<ContentPage.Content>
<StackLayout>
<views:MainMenuView />
</StackLayout>
</ContentPage.Content>
</ContentPage>
MainMenuView 自动连接到 MainMenuViewModel,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="xxx_App.Views.MainMenuView">
<ContentView.Content>
<StackLayout>
// SOME BUTTONS
</StackLayout>
</ContentView.Content>
</ContentView>
这是我的 MainMenuViewModel 构造函数:
public MainMenuViewModel(INavigationService navigationService)
{
// A breakpoint here does break the software, but navigationService is null
}
问题:问题是 MainMenuViewModel 的构造函数中的 navigationService 为空。构造函数确实被调用,所以我认为这不是自动布线的问题。构造函数被 PRISM 框架的自动连接函数调用。
有人知道为什么 navigationService 为空吗?
提前致谢!
编辑:
解决方案:我部分使用了 Roubachof 的解决方案。
我创建了一个 MainMenuPageViewModel。我摆脱了 MainMenuViewModel,因为不再需要了。我将 ICommands(在评论中提到)移到了新的 MainMenuPageViewModel。
很明显,在阅读 PRISM 时,我对页面和视图感到困惑。我以为视图有视图模型,但实际上页面有视图模型。这是因为 MVVM 和 Xamarin.Forms 使用不同的术语。既然我知道了这一点,我将去对我的应用程序的结构进行一些更改。