Search code examples
c#xamlwindows-8microsoft-metro

BlankPage constructor cannot initialize components


I'm starting learning XAML and I add some code to my BlankPage application. And suddenly a constructor which is initializing a component:

    public BlankPage()
    {
        this.InitializeComponent();
    }

Stop working. I've got now that error:

'BlankApplication.BlankPage' does not contain a definition for 'InitializeComponent' and no extension method 'InitializeComponent' accepting a first argument of type 'BlankApplication.BlankPage' could be found (are you missing a using directive or an assembly reference?)

Honestly I didn't do anything, I didn't even look at this part of code and now it doesn't work.

Screenshot:


Solution

  • If your Main class's namespace is different than .xaml file's x:Class attribute, you will get this error. For instance;

    Your MainPage.xaml.cs;

        namespace UWPControls
        {
            /// <summary>
            /// An empty page that can be used on its own or navigated to within a Frame.
            /// </summary>
            public sealed partial class MainPage : Page
            {
                public MainPage()
                {
                    this.InitializeComponent();
                }
            }
        }
    

    Your MainPage.xaml;

    <Page
        x:Class="UWPControls_Different.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:UWPHelloWorld"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    </page>
    

    You're going to see the error until changing x:class to the;

    x:Class="UWPControls.MainPage"