Home > Silverlight, Windows Phone 7 > Silverlight for Windows Phone 7: How to subclass PhoneApplicationPage

Silverlight for Windows Phone 7: How to subclass PhoneApplicationPage

     The first step is adding a cs-file with the class derived from PhoneApplicationPage:

using System;
using Microsoft.Phone.Controls;

namespace WindowsPhoneApplication1
{
    public class MyPhoneAppPage : PhoneApplicationPage
    {
        // one of your custom properties
        protected bool IsUIThread
        {
            get { return Dispatcher.CheckAccess(); }
        }
    }
}

The second step is turning the target page into a descendant of MyPhoneAppPage. To accomplish that, we need to replace all the mentions of the standard PhoneApplicationPage in the xaml-file and code-behind file with MyPhoneAppPage:

<my:MyPhoneAppPage 
    x:Class="WindowsPhoneApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:my="clr-namespace:WindowsPhoneApplication1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>        
    </Grid>
</my:MyPhoneAppPage>

Do not forget to add the xmlns:my attribute, which contains the namespace where MyPhoneAppPage is defined, to the root tag.

Sample of usage:

using System;
using Microsoft.Phone.Controls;

namespace WindowsPhoneApplication1
{
    public partial class MainPage : MyPhoneAppPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            bool parentProp = IsUIThread; // usage of the ancestor property
        }
    }
}

That’s all. Compile and enjoy. Sometimes the designer highlights xaml with a blue wavy line, as if it was a wrong markup. Don’t worry, all the “errors” disappear during the compilation.

Related posts:
 
  1. No comments yet.
  1. No trackbacks yet.