zirkelc
zirkelc

Reputation: 1713

Windows Phone - Using generic class for PhoneApplicationPage

I have a Page which consist of AddPage.xaml and AddPage.xaml.cs. I want to create a generic class AddPage which extends from PhoneApplicationPage to outsource some repetitive code like Save or Cancel. If I change the base class from PhoneApplicationPage to my new generic class, I get this error: Partial declarations of 'AddPage' must not specify different base classes.

Upvotes: 3

Views: 2219

Answers (2)

Shawn Kendrot
Shawn Kendrot

Reputation: 12465

To accomplish this you need to do the following.

First, create your base class

public class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
    protected void Save() { ... }
    protected void Cancel() { ... }
}

Then, your AddPage needs to be modified to inherit from the base class. The main places this is needed is within the code (AddPage.xaml.cs) AND within the xaml

Code:

public partial class AddPage : SaveCancelPhoneApplicationPage  {  ... }

Xaml:

<local:SaveCancelPhoneApplicationPage
    x:Class="MyPhone.Namespace.AddPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyPhone.Namespace" 
       <!-- other xaml elements -->
</local:SaveCancelPhoneApplicationPage>

UPDATE: Info added based on comments

If you need to have generic like functionality and you must use the Page to do this (rather than a ViewModel) then you can still do this using generic methods

public abstract class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
    protected override void OnNavigatedTo(blaa,blaa)
    {
        var obj = CreateMyObject();
        obj.DoStuff();
    }

    // You should know what your objects are, 
    // don't make it usable by every phone dev out there
    protected MyBaseObject MyObject { get; set; }

    protected T GetMyObject<T>() where T : MyBaseObject 
    {
        return MyObject as T;
    }
}


public class AddPage : SaveCancelPhoneApplicationPage 
{
    public AddPage()
    {
        MyObject = new MyAddObject();
    }
}

Upvotes: 5

Mani
Mani

Reputation: 1374

In order to outsource some functions you just declare some add class which does the common work. Having another page doesn't do that work.

public class Add
{
    public bool SaveContent(string filename, string content)
{
    ....//some content
    return true;
}

public string ViewContent(string filename)
{
    string content="";
    .....
    return content;
}
}

Add this part of code where you thought it is redundant.

Add obj=new Add();
obj.SaveContent("myfile.txt","Hello.This is my content.");
string content("myfile.txt"); 

Tell me if this is what you intend or not.

Upvotes: 0

Related Questions