用Prism NavigationService实例化标签页子视图模型时出现问题



在Prism Xamarin Forms应用程序中,我们已经成功地将选项卡页面的子内容页面连接到它自己的视图模型。如果ContactsScreenViewModel有一个无参数构造函数,则此操作有效。如果我们把NavigationService注入构造函数,代码就无法编译。有人知道怎么解决这个问题吗?

Visual Studio报告需要一个无参数的构造函数

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
xmlns:views="clr-namespace:TabsTest.Views"
xmlns:viewmodels="clr-namespace:TabsTest.ViewModels"
x:Class="TabsTest.Views.MainPage"
Title="{Binding Title}"
UnselectedTabColor ="Gray"
SelectedTabColor="Green"
BarBackgroundColor="LightGray">

<views:ContactsScreen BackgroundColor="White" Title="Contacts">
<views:ContactsScreen.BindingContext>
<viewmodels:ContactsScreenViewModel/>
</views:ContactsScreen.BindingContext>

<ContentPage.ToolbarItems>
<ToolbarItem  Order="Primary"
Priority="1" >
</ToolbarItem>
<ToolbarItem  Order="Primary"
Priority="0" >
</ToolbarItem>
</ContentPage.ToolbarItems>
</views:ContactsScreen>
</TabbedPage>


using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Text;
namespace TabsTest.ViewModels
{
public class ContactsScreenViewModel
{
private INavigationService _navigationService { get; }
public ContactsScreenViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
}
}
}

<viewmodels:ContactsScreenViewModel/>是一个构造函数调用…你期望这些参数从何而来?

您希望首先解析视图模型(通过工厂),然后将视图附加到它,或者使用ViewModelLocator为您解析视图模型(并解析并注入其依赖项),例如,如下所述。

<TabbedPage [...] 
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True">

将解析一个TabbedPageViewModel实例并将其放入BindingContext

应该通过属性公开ContactsScreenViewModel的实例:

<views:ContactsScreen BindingContext={Binding ThePropertyOnTabbedPageViewModel}/>

你可以创建你喜欢的实例,包括你需要的所有参数和依赖项。

最新更新