【问题标题】:Page with type parameter带类型参数的页面
【发布时间】:2015-11-14 12:50:00
【问题描述】:

我想使用 UWP 的新功能 -> x:Bind。为此,我的所有页面都需要具有 ViewModel 属性(如教程中所述)。 为了避免代码重复,我建立了如下基类:

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 属性。

然后我创建了在 xaml 中定义的派生页面“MainPage”,如下所示:

<pages:BasePage
x:Class="Realarm.View.Pages.MainPage"
x:TypeArguments="viewModel:MainVM">

通过这样做,即使是 Resharper 的 Intellisense 也为我提供了 MainPage.xaml 中“MainVM”的属性,因此可以这样写:

<ListView ItemsSource="{x:Bind VM.AlarmsVM}">

不幸的是,当我尝试构建项目时,我在 MainPage.g.i.cs 中收到错误:

严重性代码描述项目文件行 错误 CS0305 使用通用类型“BasePage”需要 1 个类型参数 Realarm D:...\Realarm\obj\x86\Debug\View\Pages\MainPage.g.i.cs 13

有什么帮助吗?

【问题讨论】:

  • 对我来说看起来不错。也许是因为你的班级被标记为abstract?您无法实例化抽象类,请尝试将其删除。
  • 当然我有派生类,我正在尝试实例化。您是否尝试过运行问题中的代码?
  • @de_ViL 你解决了吗?我遇到了同样的问题,我发现的一切都说它应该可以工作,但我得到了和你一样的错误
  • 很遗憾没有。我对界面使用了不同的方法。但这并没有解决代码重复问题。

标签: xaml generics mvvm xbind windows-10-universal


【解决方案1】:

我使用 Xamarin.Forms 完成了这项工作。

基本页面:

public abstract class BaseContentPage<TViewModel> : ContentPage where TViewModel : BaseViewModel, new()

主页.cs:

public partial class HomePage : BaseContentPage<HomeViewModel>

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>
</d:BaseContentPage>

【讨论】:

    【解决方案2】:

    只需在 XAML 顶部添加一个 x:TypeArguments 定义:

    <v:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:v="clr-namespace:YourApp.Views"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:vm="clr-namespace:YourApp.ViewModels"
                mc:Ignorable="d"
                x:TypeArguments="vm:HomeViewModel"
                x:Class="YourApp.MainPage">
    

    【讨论】:

      【解决方案3】:

      当我在基本页面的构造函数中设置 BindingContext 时,也为我工作:

          public BasePage()
          {
              BindingContext = new TBaseVM();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 2021-03-18
        • 1970-01-01
        • 2017-09-03
        • 2016-10-07
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        相关资源
        最近更新 更多