Extending a base class in XAML

Hi There

So I found myself making a bunch of views that have very similar functionality and wanted to make them extend from a base class. Originally these were custom XAML extending ContentView:

<ContentView xmlns="//xamarin.com/schemas/2014/forms"
             xmlns:x="//schemas.microsoft.com/winfx/2009/xaml"
             xmlns:layouts="clr-namespace:MyApp.Layouts"
             x:Class="MyApp.Layouts.CommentPopUp">
//Content
</ContentView>

What I was hoping I could do, was make a new class PopUpBase that extended from ContentView and implemented some of the functionality for these views, then extend that. I'm not sure how to refer to it though, trying it like this compiles but crashes when the view is displayed:

<layouts:PopUpBase xmlns="//xamarin.com/schemas/2014/forms" 
             xmlns:x="//schemas.microsoft.com/winfx/2009/xaml"
             xmlns:layouts="clr-namespace:MyApp.Layouts"
             x:Class="MyApp.Layouts.CommentPopUp">
//Content
</layouts:PopUpBase>

Is this possible? If so, how? If not, what alternatives do I have to writing out identical code for each layout?

Thanks

Answers

  • AlexVilensAlexVilens USUniversity ✭✭
    edited November 2

    My common code defined in a file similar to MyCommonPage.cs shown below, which generates a common toolbar.

    I could not copy/paste code with all those XML markers.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @AlexVilens said:
    I could not copy/paste code with all those XML markers.

    Tips for posting code so the forum parser doesn't eat it.

    I hate seeing UI created in code. XAML is not inheritable, but the class code (Csharp code behind is) - so people tend to jump on this direction and its just not a good practice.

    Instead the XAML that you want to repeat in all your UI should be done in a ControlTemplate. If you also want to inherit from a base class so you have inherited functionality (methods not UI) you can do that as well.

    I do this with my own PopupBase because I like having an auto-dismiss timer; so that is defined in the base class. But the common layout of Caption, body, ButtonGroup is all part of the ControlTempalte. Then I can derive from the base, set the XAML content as the ControlTemplate, do a couple bindings for the data... done.

Sign In or Register to comment.