Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 75885

Generic base class for a custom ContentPage

$
0
0

The last Xamarin.Forms release notes had this comment:

  • [XAML] x:TypeArguments now works at root level, fixing generic subclassing from XAML

That sounds like exactly what I'm trying to do, but I'm struggling to come up with the right syntax to make it work.

I have a base class for all of my custom pages:

public class PageBase<TViewModel> : ContentPage
    where TViewModel : ViewModel
{
    public TViewModel ViewModel { get { return BindingContext as TViewModel; } }
}

Then one of my custom pages looks something like this:

public class MyPage : PageBase<MyPageViewModel>
{
    // ...
}

The hard part is figuring out how to write MyPage.xaml. Here is what I have tried:

<?xml version="1.0" encoding="UTF-8"?>
<local:PageBase
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:App.View.Pages;assembly=App"
    x:Class="App.View.Pages.MyPage"
    x:TypeArguments="App.ViewModel.Pages.MyPageViewModel">
    <!-- ... -->
</local:PageBase>

When I build this I get a compile error because the generated MyPage.xaml.g.cs file looks like this:

public partial class MyPage : global::App.View.Pages.PageBase {
    private void InitializeComponent() {
        this.LoadFromXaml(typeof(MyPage));
    }
}

The error is that there is no type specifier for the base class. It should look like this:

public partial class MyPage : global::App.View.Pages.PageBase<global::App.ViewModel.Pages.MyPageViewModel> {
    private void InitializeComponent() {
        this.LoadFromXaml(typeof(MyPage));
    }
}

Based on the line in the release notes I believe this is possible, but I must be missing something. How can I make this do what I want it to do?


Viewing all articles
Browse latest Browse all 75885

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>