带有类型参数的页面 [英] Page with type parameter
问题描述
我想使用UWP的新功能-> x:Bind.为此,我所有的页面都需要具有ViewModel属性(如教程中所述).为了避免代码重复,我建立了如下基类:
I would like to use new feature of UWP -> x:Bind. In order to that, all my pages need to have ViewModel property (as described in tutorials). To avoid code duplicity, I have established base class as follows:
public abstract class BasePage<TBaseVM> : Page, where TBaseVM : BaseVM
{
public TBaseVM VM { get; private set; }
protected BasePage()
{
DataContextChanged += (s, e) => VM = e.NewValue as TBaseVM;
}
}
如您所见,此BasePage类包含名为"VM"的属性,并且该属性的类型为BaseVM.因此,我不需要在每个派生类上定义VM属性.
As you can see this BasePage class contains property called "VM" and property is of type BaseVM. Hence, I don't need to define VM property on each derived class.
然后我创建了在xaml中定义的派生页面'MainPage',如下所示:
Then I created derived page 'MainPage' defined in xaml as follows:
<pages:BasePage
x:Class="Realarm.View.Pages.MainPage"
x:TypeArguments="viewModel:MainVM">
这样做,即使Resharper的Intellisense也可以通过MainPage.xaml中的"MainVM"为我提供属性,因此可以编写:
By doing that, even Resharper's Intellisense offers me properties from "MainVM" in MainPage.xaml, thus is can write:
<ListView ItemsSource="{x:Bind VM.AlarmsVM}">
不幸的是,当我尝试构建项目时,在MainPage.g.i.cs中出现错误:
Unfortunately, when I try to build the project, I get error in MainPage.g.i.cs:
严重性代码描述项目文件行错误CS0305使用通用类型'BasePage'需要1个类型参数Realarm D:... \ Realarm \ obj \ x86 \ Debug \ View \ Pages \ MainPage.g.i.cs 13
Severity Code Description Project File Line Error CS0305 Using the generic type 'BasePage' requires 1 type arguments Realarm D:...\Realarm\obj\x86\Debug\View\Pages\MainPage.g.i.cs 13
有帮助吗?
推荐答案
我使用Xamarin.Forms进行了这项工作.
I got this working using Xamarin.Forms.
基本页面:
public abstract class BaseContentPage<TViewModel> : ContentPage where TViewModel : BaseViewModel, new()
HomePage.cs:
HomePage.cs:
public partial class HomePage : BaseContentPage<HomeViewModel>
HomePage.xaml:
HomePage.xaml:
<d:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="clr-namespace:Sample.Pages;assembly=Sample" xmlns:vm="clr-namespace:Sample.ViewModels;assembly=Sample" x:Class="Sample.Pages.HomePage" x:TypeArguments="vm:HomeViewModel">
<ContentPage.Content>
</ContentPage.Content>
这篇关于带有类型参数的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!