Initializecomponent c ошибка

Since this seems to be the go-to thread for the problem regarding missing ‘InitializeComponent’, I’ll include my answer here.

I too was having this issue and I’ve tried everything I found here and in all other Forums that Google could find, however none resolved the issue for me. After two hours of trying everything, I finally figured out what was wrong with my setup.

In our project, we are using Metro components from MahApps. The view that was giving me trouble was a view inheriting from MetroWindow, like this:

<Controls:MetroWindow x:Class="ProjectNamespace.MyView"
                      xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
                      ... >

Now, I have defined my static resources as

<Controls:MetroWindow.Resources>
    <prop:Resources x:Key="LocalizedStrings"/>
    ...
</Controls:MetroWindow.Resources>

That’s how I’ve defined Resources in UserControls in all my other views, so that’s what I assumed will work.

That was, however, not the case with Controls:MetroWindow! There I absolutely needed the resource definition as follows:

<Controls:MetroWindow.Resources>
    <ResourceDictionary>
        <prop:Resources x:Key="LocalizedStrings"/>
        ...
    </ResourceDictionary>
</Controls:MetroWindow.Resources>

So my issue, in summary, was a missing <ResourceDictionary> tag. I really don’t know why this produced the ‘InitializeComponent’ error and it weirdly didn’t even produce it on every machine of mine, but that’s how I fixed it. Hope this helps (the remaining 0.001% of people encountering this issue).

I wanted to learn about building files with c# so I created a Windows Forms Application and I created this code/form. But It did not seem to work.
.

enter image description here

using System;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace teztie
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "*.exe |*.exe";
            DialogResult result = sfd.ShowDialog();
            if (result == DialogResult.OK)
            {
                build(sfd.FileName, textBox1.Text, textBox2.Text);
            }
        }

        private void build(string output, string msg, string name)
        {
            CompilerParameters p = new CompilerParameters();
            p.GenerateExecutable = true;
            p.ReferencedAssemblies.AddRange(new string[] { "System.dll", "System.Windows.Forms.dll"});
            p.OutputAssembly = output;
            p.CompilerOptions = "/t:winexe";

            string source = Properties.Resources.source;
            string errors = string.Empty;

            source = source.Replace("[MSG]", msg);
            source = source.Replace("[NAME]", name);

            CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);

            if (results.Errors.Count > 0)
            {
                foreach (CompilerError err in results.Errors)
                {
                    errors += "Error: " + err.ToString() + "\r\n\r\n";
                }
            }
            else
            {
                errors = "Successfully built:\n" + output;
            }

            MessageBox.Show(errors, "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

Source.Txt:

using System;
using System.Windows.Forms;

namespace code
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("[msg]",  "[title]" );
        }
    }
}

But when I click the compile button it gives me an error.
The name InitializeComponent does not exist in the current context.

enter image description here

Привет. Я получаю сообщение об ошибке InitializeComponent на моей странице app.xaml.cs. Я проверил сеть и все, но решение не работает. Пожалуйста, помогите.

InitializeComponent не существует

Файл С#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace Miser_sApp
{
     public partial class App : Application
    {
          /// <summary>
         /// Provides easy access to the root frame of the Phone Application.
         /// </summary> 
         /// <returns>The root frame of the Phone Application.</returns>
          public PhoneApplicationFrame RootFrame { get; private set; }

         /// <summary> 
         /// Constructor for the Application object.
         /// </summary>
        public App()
         {
             // Global handler for uncaught exceptions. 
              UnhandledException += Application_UnhandledException;

             // Standard Silverlight initialization
             InitializeComponent();

             // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                 // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application PhoneApplicationService object to Disabled.
                 // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

       }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

         // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
       {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender,    ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
       }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
             // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
             RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}

Файл XAML:

<Application 
    x:Class="Miser_sApp.App"
    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">

    <!--Application Resources-->
    <Application.Resources>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

Я загрузил содержимое app.xaml.
Я не внес никаких изменений.

  • Remove From My Forums
  • Question

  • User173360 posted

    Hi,

    The error CS0103 (The name ‘InitializeComponent’ does not exist in the current context) has started appearing after doing a build of our Xamarin Forms solution. The build, however, appears to have succeeded in spite of this error message?

    This started happening after adding the first XAML ContentPage to the PCL project. If I remove the XAML ContentPage then the error disappears.

    I’ve tried installing the latest Alpha channel update on both my Windows (Visual Studio) machine and my Mac build host but it hasn’t made any difference.

    Please advise ASAP as we would like to use XAML for our ContentPages but may have to revert to using C# code to build the UI if the XAML approach is not viable.

    Regards,
    Andy

UWP app project showing Intellisense error with a new, from template Xamarin.Forms solution using a Shared project type.

Error CS0103 The name ‘InitializeComponent’ does not exist in the current context App1.UWP
is shown in the errors pane.

The first time I tried to reproduce it, I got a build error and the UWP app project build failed, as described in the forum post. Cleaning and rebuilding resolved the build error but the Intellisense error remained only for the UWP app project.

I then tested again, creating a new template project of the same type. This second time there was no build error, but the Intellisense error was shown for all three app platform projects. At some point, after cleaning and rebuilding and selecting the iOS app project as the startup project, the INtellisense error went away for the iOS app project, but remained for Android and UWP.

I tried closing and re-opening the solutions as well as closing and re-opening the IDE. At some point the Intellisense errors went away. I closed the IDE and re-opened the second solution I created, opened the properties pages to get some info for the bug report, i.e. target frameworks, and the Intellisense errors went away. Not sure after which specific action they disappeared, but it seems to me this was a dance that should not need to be done.

Version Info
Microsoft Visual Studio Enterprise 2017
Version 15.7.2
VisualStudio.15.Release/15.7.2+27703.2018
Microsoft .NET Framework
Version 4.7.03056

Installed Version: Enterprise

Application Insights Tools for Visual Studio Package 8.12.10405.1
Application Insights Tools for Visual Studio

ASP.NET and Web Tools 2017 15.0.40511.0
ASP.NET and Web Tools 2017

ASP.NET Core Razor Language Services 15.7.31476
Provides languages services for ASP.NET Core Razor.

ASP.NET Web Frameworks and Tools 2017 5.2.60419.0
For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0 15.0.40424.0
Azure App Service Tools v3.0.0

Azure Data Lake Node 1.0
This package contains the Data Lake integration nodes for Server Explorer.

Azure Data Lake Tools for Visual Studio 2.3.3000.2
Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools 15.0.40424.0
Azure Functions and Web Jobs Tools

Azure Stream Analytics Tools for Visual Studio 2.3.3000.2
Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools 2.8.2-beta6-62916-08. Commit Hash: 2ad4aabc7a9dada097e54e544ebba48ab1c05074
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Fabric.DiagnosticEvents 1.0
Fabric Diagnostic Events

GitHub.VisualStudio 2.2.0.10
A Visual Studio Extension that brings the GitHub Flow into Visual Studio.

JavaScript Language Service 2.0
JavaScript Language Service

JavaScript Project System 2.0
JavaScript Project System

JavaScript UWP Project System 2.0
JavaScript UWP Project System

Merq 1.1.19-rc (a4ffc1b)
Command Bus, Event Stream and Async Manager for Visual Studio extensions.

Microsoft Azure HDInsight Azure Node 2.3.3000.2
HDInsight Node under Azure Node

Microsoft Azure Hive Query Language Service 2.3.3000.2
Language service for Hive query

Microsoft Azure Service Fabric Tools for Visual Studio 2.1
Microsoft Azure Service Fabric Tools for Visual Studio

Microsoft Azure Stream Analytics Language Service 2.3.3000.2
Language service for Azure Stream Analytics

Microsoft Azure Stream Analytics Node 1.0
Azure Stream Analytics Node under Azure Node

Microsoft Azure Tools 2.9
Microsoft Azure Tools for Microsoft Visual Studio 2017 — v2.9.10420.2

Microsoft Continuous Delivery Tools for Visual Studio 0.3
Simplifying the configuration of continuous build integration and continuous build delivery from within the Visual Studio IDE.

Microsoft JVM Debugger 1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft MI-Based Debugger 1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual Studio Tools for Containers 1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package 1.0
Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio 4.10.5-pre (ab58725)
Support for debugging Mono processes with Visual Studio.

Node.js Tools 1.4.11027.3
Adds support for developing and debugging Node.js apps in Visual Studio

NuGet Package Manager 4.6.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

ProjectServicesPackage Extension 1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

ResourcePackage Extension 1.0
ResourcePackage Visual Studio Extension Detailed Info

Snapshot Debugging Extension 1.0
Snapshot Debugging Visual Studio Extension Detailed Info

SQL Server Data Tools 15.1.61804.210
Microsoft SQL Server Data Tools

ToolWindowHostedEditor 1.0
Hosting json editor into a tool window

TypeScript Tools 15.7.20419.2003
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools 2.8.2-beta6-62916-08. Commit Hash: 2ad4aabc7a9dada097e54e544ebba48ab1c05074
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.1 for F# 4.1 15.7.0.0. Commit Hash: 56f97a8dd4353d897336941f3e644423b87c794f.
Microsoft Visual F# Tools 10.1 for F# 4.1

Visual Studio Code Debug Adapter Host Package 1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Tools for Apache Cordova 15.123.7408.1
Visual Studio Tools for Apache Cordova

Visual Studio Tools for Universal Windows Apps 15.0.27703.2018
The Visual Studio Tools for Universal Windows apps allow you to build a single universal app experience that can reach every device running Windows 10: phone, tablet, PC, and more. It includes the Microsoft Windows 10 Software Development Kit.

VisualStudio.Mac 1.0
Mac Extension for Visual Studio

Windows Machine Learning Generator Extension 1.0
Windows Machine Learning Visual Studio Extension Detailed Info

Xamarin 4.10.0.448 (4373404db)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer 4.12.270 (82d750d12)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin.Android SDK 8.3.0.19 (HEAD/342b2ce96)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK 11.10.1.178 (408d357)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Понравилась статья? Поделить с друзьями:
  • Initializeatkacpidevice returns false как исправить ошибку
  • Inst 02987 03 ошибка ман тга
  • Inspire electrolux стиральная машина ошибка e10
  • Inspector flo ошибка
  • Ins 3720 ошибка атего