Alex Rivera | Logout

Why can't Visual Studio find my WPF InitializeComponent method?

Asked 2009-06-05T08:41:49.603
52

This is very strange.

I have an XAML file that looks as follows...

<Window
    x:Name="window"
    x:Class="ix.Production.Title"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Title" Height="768" Width="1024"
    Loaded="window_Loaded">

    <Window.Resources>
   etc...

And my code-beside that looks as follows...

using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Threading;

namespace ix.Production
{
    public partial class Title : Window
    {
        public Title()
        {
           InitializeComponent();
        }
    ....

This code refuses to compile because Visual Studio insists that the InitializeComponent "does not exist in the current context."

How can I fix this problem?

wpf
Edit
Report

4 Answers

18

So simple, but so easy to overlook: MainWindow's x:Class was set to "MainWindow", when it should have been set to namespace.MainWindow (x:Class="namespace.MainWindow"). If this is not done, then the MainWindow.g.xaml file will not include a namespace block, and the call to InitializeComponent() in MainWindow's constructor will not work.

Although this obviously isn't a solution to willem's problem, I posted it here because there are so many other solutions listed. Hopefully this will help someone else who stumbles on this post when trying to fix their problem.

answered 2011-03-08T13:26:11.350
2

I usually get this problem when renaming custom control classes, or, as in your case, changing the name of the class's namespace. If you don't use Visual Studio's refactoring, then you have to manually change the names in both XAML and C# files.

Refactoring is only good when you just rename the class, for namespace rename, you have to do it manually.

For InitializeComponent, look in [Project Folder]\obj\Debug\<class_name.g.cs>.

answered 2011-04-02T07:25:03.443
1

Looks like this was a kink in Visual Studio 2008.

If I create a new file (i.e. Title2), copy/paste the code and XAML, then change all 'Title' to 'Title2', everything works fine again.

answered 2009-06-05T09:38:54.340
0

FWIW, I hit the same problem today after migration of a Visual Studio 2008 solution to Visual Studio 2010. It appears that the migration goofed and the projects lost their Target Framework (in Project Properties): The setting is now empty!?

Setting .NET Framework 3.5 solved the problem.

answered 2011-09-06T09:35:21.923

Your Answer