Display Name
Display Name

Reputation: 15081

How to set MainPage from App.xaml instead of App.xaml.cs?

I want to learn how to set MainPage property of App to MyPage inheriting from ContentPage. In App.xaml.cs it can be easily done as follows.

public partial class App : Application
{

    public App()
    {
        InitializeComponent();

        MainPage = new MyPage();
    }

}

How to do the same thing but from within the XAML?

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             mc:Ignorable="d"
             x:Class="MyProject.App">

    <!-- Others have been removed only for simplicity! -->
    <Application.MainPage>
       <!-- I don't know what I have to do here. -->       
    </Application.MainPage>
</Application>

Upvotes: 1

Views: 473

Answers (2)

Display Name
Display Name

Reputation: 15081

Another approach:

<Application <!--remove for simplicity-->                 
             MainPage="{StaticResource myPage}">
    <Application.Resources>
        <ResourceDictionary>
            <local:MyPage x:Key="myPage"/>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Upvotes: 0

Jason
Jason

Reputation: 89082

you need to declare a local namespace

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         mc:Ignorable="d"
         xmlns:local="clr-namespace:MyNamespace"
         x:Class="MyProject.App">


<Application.MainPage>
   <local:MyPage />    
</Application.MainPage>

Upvotes: 2

Related Questions