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 UserControl
s 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.
.
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() + "rnrn";
}
}
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.
Vlast001 30 / 14 / 7 Регистрация: 08.01.2019 Сообщений: 636 |
||||
1 |
||||
09.11.2020, 15:37. Показов 10067. Ответов 9 Метки нет (Все метки)
Имя «InitializeComponent» не существует в текущем контексте
Что делать? Подскажте пожалуйста, срочно нужно это решить, такая шляпа в нескольких классах созданных автоматически после создания UserContol xaml файла P.S. WPF .Net core
0 |
Модератор 13806 / 10013 / 2666 Регистрация: 21.04.2018 Сообщений: 29,806 Записей в блоге: 2 |
|
09.11.2020, 16:03 |
2 |
такая шляпа в нескольких классах созданных автоматически после создания UserContol xaml файла Какой-то геморр с пространствами имён: названия папок совпадающее с типами, разные пhостранства в XAML и в CB и т.п. По этому коду ничего не скажешь.
0 |
1006 / 625 / 212 Регистрация: 08.08.2014 Сообщений: 1,943 |
|
09.11.2020, 16:03 |
3 |
Т.е. если создать новый стандартный ‘UserControl’ через мастер и ничего не менять, то ошибка стабильно повторяется? Или же вы что-то поменяли в XAML? Вариант наиболее вероятный — вы что-то сами сломали в коде, например, удалили/подредактировали атрибут ‘x:Class’ в разметке. Вариант маловероятный: Вариант очень маловероятный — у вас какая-то древняя промежуточная превью-версия студии, в которой был какой-нибудь проходной баг, который давно пофиксили.
1 |
30 / 14 / 7 Регистрация: 08.01.2019 Сообщений: 636 |
|
09.11.2020, 16:15 [ТС] |
4 |
По этому коду ничего не скажешь. А что вам показать? Проект большой(по крайне меря для меня)
названия папок совпадающее с типами, разные пhостранства в XAML и в CB и т.п. Что это значит?
у вас какая-то древняя промежуточная превью-версия студии, Не знаю, но в списке обновлений есть только «Доступно обновление для «ML.NET Model Builder (Preview)» «
2. Из каталога проекта удалить каталоги ‘bin’ и ‘obj’. Именно это устал пробовать, щас попробую все 4 пункта
если создать новый стандартный ‘UserControl’ через мастер и ничего не менять То конструктор будет просить восстановить Кэш с пакетов Nuget и я не знаю как это делать
0 |
1006 / 625 / 212 Регистрация: 08.08.2014 Сообщений: 1,943 |
|
09.11.2020, 16:31 |
5 |
То конструктор будет просить восстановить Кэш с пакетов Nuget и я не знаю как это делать Конструктор? Если у вас корректно установлена VS, если она (и её утилиты) имеет доступ в интернет, и если вы создаёте типовой WPF-проект под .NET Core, то никаких проблем при добавлении нового UC возникать не должно. Попробуйте, для теста, просто создать типовой (по шаблону VS) WPF-проект с одним главным окном. Собрать его, запустить. Ок. Далее, добавить, через мастер, обычный UserControl. Снова собрать. Если эти сценарии не работают, значит у вас окружение сломано.
0 |
30 / 14 / 7 Регистрация: 08.01.2019 Сообщений: 636 |
|
09.11.2020, 17:17 [ТС] |
6 |
Конструктор?
1. Закрыть все экземпляры студии. Помогло, я еще перед этим VS Istaller зашел, попытался обновить и вдобавок виндовс перезапустил на всякий случай))) kotelok, Элд Хасп, Посмотрите на вложение, пожалуйста. Я думал ошибка из-за Имя «InitializeComponent» не существует в текущем контексте, но теперь то InitializeComponent работает. Да и почему не существует пространства имен, если внутри студия сама подсказывает что писать даже в пунтке lab3:MainLab3ViewModel студия помогает, но все равно есть ошибки с первого вложения и причем ошибки возникают при попытке компиляции и потом висят как просто ошибки. Вложение 2 это что будет, если убрать содержимое DataContext, как видно там пропадает почти половина всего UI. P.S. Можно это решить здесь без создания новой темы?) Миниатюры
0 |
Модератор 13806 / 10013 / 2666 Регистрация: 21.04.2018 Сообщений: 29,806 Записей в блоге: 2 |
|
09.11.2020, 17:21 |
7 |
Посмотрите на вложение. Покажите начало файла с классом
0 |
Vlast001 30 / 14 / 7 Регистрация: 08.01.2019 Сообщений: 636 |
||||
09.11.2020, 18:28 [ТС] |
8 |
|||
Решение
С первой строчки файла, до строки с объявлением класс.
Добавлено через 49 минут Такой алгоритм: Надеюсь это кому-то тоже поможет. P.S. надеюсь я ничего не сломаю, когда добавлю еще один пользовательский элемент управления
2 |
Модератор 13806 / 10013 / 2666 Регистрация: 21.04.2018 Сообщений: 29,806 Записей в блоге: 2 |
|
09.11.2020, 19:22 |
9 |
Такой алгоритм: Что-то вы очень нетипичное делали со Студией, раз глюк в этот оказался.
0 |
0 / 0 / 0 Регистрация: 19.04.2020 Сообщений: 13 |
|
24.06.2022, 23:21 |
10 |
Весьма гадская ошибка. Столкнулся с этим на VS 2022. Пробовал подключить к своему проекту сворачивание окна в трей по чьему-то мануалу. В итоге мануал оказался кривой и я откатил все изменения в файлах Ctrl+Z на изначальные, а в итоге получил «эту прелесть». Целый проект, который дорабатывал больше года, стал нерабочим.
0 |
Привет. Я получаю сообщение об ошибке 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.
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.
Если я создаю новый проект в Visual Studio 2010 с пакетом обновления 1 (SP1) и выбираю «Приложение WPF» и пытаюсь создать сгенерированное приложение, я получаю сообщение об ошибке
Имя InitializeComponent не существует в текущем контексте.
Сегодня утром я получил похожую ошибку, когда попытался построить свой текущий проект. Вчера у меня не было проблем с его компиляцией и запуском.
Я создал новый проект и получал сообщение об ошибке при компиляции проекта. Я только что отправил проект коллеге, и он только что скомпилировал без ошибок.
Что случилось?
Ответ 1
Я столкнулся с этим пару раз и продолжаю забывать, что его вызывает.
Я столкнулся с этим, когда переименовал пространство имен в свой код за файлом, но не в свой XAML.
Итак, проверьте, сделали ли вы то же самое.
Названия namespace и class должны совпадать, поскольку они являются частью частичного класса
namespace ZZZ
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
//...
}
}
<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">
Ответ 2
Действие сборки для файла .xaml также должно быть установлено на «Страница», при перемещении файла xaml между проектами этот параметр теряется (по крайней мере, в VS 2010).
Ответ 3
Для тех, у кого нет ошибок в режиме отладки, но есть указанная ошибка в режиме выпуска (и все же проект работает нормально), попробуйте выполнить следующее:
- Откройте файл XAML, соответствующий нарушающему файлу xaml.cs.
- Сделайте правку — любую правку, например, добавьте пробел где-нибудь
- Сохраните файл и закройте его
Этот метод работал для меня в VS 2015, и, по словам других пользователей, также 2017 и 2019
Ответ 4
Здесь есть очень конкретная причина, и это в настройках проекта. Это обычно происходит, когда вы пытаетесь добавить элемент управления WPF/окно в библиотеку или проект класса .NET 2.0. Причина этой ошибки в том, что проект не знает, что он создает элемент управления WPF или окно и поэтому пытается построить его как проект С# 2.0.
Решение включает в себя редактирование файла .csproj. Щелкните правой кнопкой мыши на проекте, вызывающем проблему, и выберите «Выгрузить проект». Щелкните правой кнопкой мыши выгруженный проект и выберите «Изменить .csproj». Откроется файл .csproj, и вы увидите XML. найдите следующую строку:
<Import Project=…..
Это ближе к концу файла, и единственная строка, которая у вас есть, вероятно,
<Import Project="$(MSBuildBinPath)Microsoft.CSharp.targets" />
Это говорит Visual Studio, что проект будет реализован как проект .NET 2.0. Мы хотим сказать, что Visual Studio это проект WPF, поэтому мы должны добавить следующую строку:
<Import Project="$(MSBuildBinPath)Microsoft.WinFX.targets" />
В этой строке Visual Studio будет строить проект как проект WPF. Теперь ваше дно файла .csproj должно выглядеть следующим образом:
<Import Project="$(MSBuildBinPath)Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)Microsoft.WinFX.targets" />
Сохраните файл .csproj, щелкните его правой кнопкой мыши в обозревателе решений и выберите «Перезапустить проект», и все, что вы сделали!
Ответ 5
- Перейдите в каталог решений
- Удалить папку obj
- Восстановить решение
Я столкнулся с этой ошибкой во время рефакторинга, где я переименовал некоторые файлы/папки, и файлы предварительного кодирования *.g.cs, необходимые для повторного создания.
Ответ 6
это произошло со мной, когда я случайно удалил ссылку на класс из определения xaml:
Я заменил
<Window x:Class="myapp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
первая строка с этим:
<RibbonWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
Я знаю, что это не ответ на исходный вопрос (потому что этот проект строится на другой машине), но сообщение об ошибке было одинаковым, поэтому, возможно, я помогу кому-то в этой ситуации.
Ответ 7
Убедитесь, что в файле xaml
<Page x:Class="Project1.Page1" ...
соответствуют имени ‘Project1’ и имени ‘Page1
Ответ 8
Вы можете получить эту ошибку при импорте класса из другого проекта или изменении пути к файлу xaml или в пространстве имен файла xaml или за .cs.
Один: У него может быть пространство имен, которое не совпадает с тем, что у вас есть в новом проекте
namespace TrainerB.MVC.Forms
{
public partial class AboutDeveloper : ContentPage
{
public AboutDeveloper()
{
InitializeComponent();
}
}
}
Как вы видите, пространство имен в импортированном файле начинается со старого имени проекта: «TrainerB» , но ваш новый проект может иметь другое имя, поэтому просто измените его на правильный новый имя проекта, как в файле .xaml, так и в файле .cs.
Два:
измените свойства файла .xaml на:
Действие сборки: Встроенный ресурс
Пользовательский инструмент: MSBuild: UpdateDesignTimeXaml
Ответ 9
У меня было это (хотя это была моя большая ошибка и была вызвана после того, как я скопировал и вставил некоторый код в); это может произойти, когда пространство имен не совпадает между XAML и кодом
EG
<UserControl x:Class="DockPanel.TreeView" />
и код
namespace NotDockPanel
Ответ 10
Я столкнулся с этим, переименовав usercontrol. То, как я исправил это, — это прокомментировать InitializeComponent, убедиться, что все имена были правильными (xaml и код позади), построить проект, раскомментировать InitializeComponent, а затем снова построить. Похоже, что может быть несколько причин/решений для этой проблемы, но этот способ сделал это для меня.
Ответ 11
Проверьте файл Designer.
У меня была такая же проблема. В моем случае причина была в том, что namespace
для FileName.Designer.cs не соответствует (правильному) namespace
, используемому в FileName.cs.
Изменение namespace
FileName.Designer.cs для соответствия с FileName.cs решило проблему немедленно.
Ответ 12
Ни один из вышеперечисленных ответов не работал у меня. Я попробовал их всех, кроме дубликатов. Однако по какой-то странной причине это работало в моем кросс-платформенном проекте в Visual Studio 2015:
- Щелкните правой кнопкой мыши проект, который вызывает проблему в обозревателе решений. Во всплывающем меню выберите: Добавить → Класс
- Выберите кросс-платформенную страницу → Forms Xaml. Сохраните стандартное имя стандартного Page1.cs и нажмите «Добавить».
- Обратите внимание, что предыдущая проблема InitializeComponent() исчезла по какой-то причине.
- Удалить вновь созданный файл Page1.cs и продолжить программирование, как если бы Visual Studio работала нормально.
Ответ 13
Я согласен с вышеприведенным ответом, что пространства имен должны совпадать. Тем не менее, у меня была проблема, подобная этой, где совпадали пространства имен.
Чтобы исправить, я просто изменил пространство имен в XAML на INCORRECT, сохраненный, а затем изменил его на CORRECT. Вуаля!
Ответ 14
Разгрузите все решение, а затем снова загрузите его. Затем перестройте решение. Это разрешило проблему для меня.
Ответ 15
Если вы используете Xamarin Forms, и вы перемещаете файл XAML, «действие сборки» файла изменяется. Xamarin Forms требует «build action = Embedded Resource».
Применить «действие сборки» в Visual Studio:
Select the XAML file -> Properties -> Build Action = Embedded Resource
Ответ 16
Другой распространенной причиной этой ошибки является то, что вы сделали что-то в этом:
-
Щелкните правой кнопкой мыши по папке в проекте, чтобы создать новый UserControl. Это создает файл класса и xaml, который выводится из пользовательского элемента управления в пространстве имен папки.
-
Затем вы решите изменить пространство имен класса, потому что вы действительно используете папки для организации кода. Атрибут x: Class не будет автоматически обновляться, поэтому он будет искать класс, который не существует. Вероятно, возможно использовать лучшее сообщение об ошибке типа «x: Class не может быть найдено в namesace bla.blaa.blaaa.»
Ответ 17
Я пробую все предложения выше. Если вы попробуете слишком без успеха, получите более простой способ. Создайте новый page.xaml, затем скопируйте код для нового класса и удалить класс XAML с проблемами. Не трать больше времени.
Ответ 18
Другим решением этой проблемы является простое изменение свойства- > Строить действие на XAML из Embedded Resource на что-либо еще, сохранить, а затем изменить его прямо на Embedded Resource. Ошибка исчезнет.
Ответ 19
Я знаю, что на это ответили по другой причине, но это очень популярное сообщение, и я столкнулся с той же проблемой с библиотекой классов. В этом случае это оказалось как изменением в моем пространстве имен (ответ в этом посте здесь), так и тем, что компилятор не смог перестроить Window.g.i.cs, который определяет метод InitializeComponent(). Не удалось, потому что в библиотеке классов отсутствовало значение ProjectTypeGuid для проектов WPF в файле csproj. Инструкции для этого приведены здесь и здесь. Я думал, что поделюсь, если кто-то столкнется с той же проблемой. В этом случае недостаточно просто изменить пространство имен.
Ответ 20
Это произошло со мной, потому что деинсталлятор пакета Nuget сдул все атрибуты в <Application> элемент в App.xaml. Это включает атрибут x: Class, который определяет имя класса приложения. Поэтому неполный класс, содержащий метод InitializeComponent(), никогда не генерировался.
Я исправил проблему, вернув App.xaml в исходную копию.
Ответ 21
Это решило это для меня.
Я прокомментировал ресурсы в файле App.xaml
<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<!--<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>-->
</Application.Resources>
</Application>
Комментирование ответа на исправление ошибки сборки.
<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Копая немного глубже, я обнаружил, что файл app.g.cs в {Project}objdebug содержал только следующее, когда я покинул ресурс, прокомментированный.
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/MyApp;component/app.xaml", System.UriKind.Relative);
#line 1 "......App.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
Ответ 22
Для тех, кто находит это в Интернете. Проверьте файл Windows.csproj, если существует компиляция. Должно быть 2 записи
<Page Include="YourFile.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Compile Include="YourFile.xaml.cs">
<DependentUpon>YourFile.xaml</DependentUpon>
</Compile>
Ответ 23
Если пространства имен верны, то также есть одна и та же ошибка,
Просто закройте приложение и откройте его снова.
Это может решить вашу проблему.
Ответ 24
После некоторого действия пространство имен файла .cs и файла в .xaml может быть другим (в xaml найдите x: Class= «namespace.yourType» ).
Исправьте их одинаковыми.
Ответ 25
Я обнаружил, что «объект запуска» был (не задан), вызвав эту ошибку для меня.
«Объект запуска» (не задано)
Ответ 26
Так как это, по-видимому, относится к теме, касающейся отсутствия «InitializeComponent», я включу здесь свой ответ.
У меня тоже была эта проблема, и я пробовал все, что нашел здесь и на всех других форумах, которые Google мог найти, однако ни одна проблема не разрешила меня. После двух часов попыток все, я наконец понял, что случилось с моей настройкой.
В нашем проекте мы используем компоненты Metro из MahApps. Представление, которое вызывало у меня проблемы, было видом, наследующим от MetroWindow, следующим образом:
<Controls:MetroWindow x:Class="ProjectNamespace.MyView"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
... >
Теперь я определил свои статические ресурсы как
<Controls:MetroWindow.Resources>
<prop:Resources x:Key="LocalizedStrings"/>
...
</Controls:MetroWindow.Resources>
То, как я определил ресурсы в UserControl
во всех моих других представлениях, так что то, что я предположил, будет работать.
Это было, однако, не в случае с Controls:MetroWindow
! Там мне абсолютно необходимо определение ресурса следующим образом:
<Controls:MetroWindow.Resources>
<ResourceDictionary>
<prop:Resources x:Key="LocalizedStrings"/>
...
</ResourceDictionary>
</Controls:MetroWindow.Resources>
Итак, моя проблема, в общем, отсутствовала тег <ResourceDictionary>
. Я действительно не знаю, почему это произвело ошибку InitializeComponent, и это странно даже не производило ее на каждой моей машине, но так, как я ее исправил. Надеюсь, что это поможет (оставшиеся 0.001% людей сталкиваются с этой проблемой).
Ответ 27
Итак, я понимаю, что это старый вопрос, но у нас была аналогичная проблема. Мы смогли построить проект с использованием VS2012, но не используя msbuild из командной строки. Я зашел в файл .proj и заметил, что у него нет записи для «ProjectTypeGuids» в разделе «PropertyGroup» по умолчанию, поэтому я добавил следующее:
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
который является GUID проекта для WPF. Затем я удалил и снова добавил UserControl, и он начал работать. Я не уверен, должен ли я сделать этот последний шаг, но теперь он работает для меня.
Ответ 28
Я только столкнулся с этой проблемой, и оказалось, что мой проект хранится в моей папке пользователя, которая хранится в сети, и у нас был кратковременный перерыв в сети. Я сделал сборку; он жаловался, что мои файлы были изменены вне редактора (у них не было, блокировки файлов только что были обработаны), и он был создан отлично, удалив ошибку в отношении метода InitializeComponent()
.
Кстати, если вам интересно, разработка чего-то с сетевого диска — это плохая практика. Это становится особенно проблематичным, когда вы пытаетесь использовать управляемый код .NET; по моему опыту, он волнуется каждый раз, когда вы строите. Я забыл положить этот маленький проект выброса в правильную папку и в итоге заплатил цену.
Ответ 29
Другим возможным объяснением является то, что вы создаете против x86. Щелкните правой кнопкой мыши свое решение и выберите Configuration Manager. Посмотрите, строите ли вы против x86 вместо Any CPU.
Ответ 30
По какой-то причине после копирования .xaml и его .cs между проектами, действие сборки иногда меняется. Убедитесь, что для сборки .xaml создана страница.
Добрый день.
Разрабатывают приложение работающее с условными файлами. И необходимо открывать файлы некоторого разрешение по дабл клику. Делать пока решил без записей в регистр, а просто через открыть с помощью и указанием пути до файла.
Код App.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args.Length != 0)
{
Uri uri = new Uri(e.Args[0]);
this.Properties["ArbitraryArgName"] = uri.LocalPath;
ASKD.MainWindow window = new ASKD.MainWindow();
window.Show();
}
}
В MainWindow на методе Loaded пишу следующее:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { // запустится когда все дети загрузятся
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
CurrentPath = Application.Current.Properties["ArbitraryArgName"].ToString();
if (File.Exists(CurrentPath))
{
//делаю всякое
}
}
}));
В итоге — приложение не запускается. Вернее доходит до InitializeComponent() в MainWindow и на это благополучно ничего не происходит. Однако, если открыть файл в одной папке с exeшником, то чудо происходит. Как решить такую проблему?
Спасибо.
The ‘The name ‘InitializeComponent’ does not exist in the current context’ error is a common issue that developers face while working with .Net MAUI (Multi-platform App UI) projects in C#. This error occurs when the InitializeComponent method is not found in the current context and is usually related to the XAML design code behind file not being properly linked to the main code file.
Method 1: Verify XAML Design Code Behind Link
To fix the build errors caused by the missing ‘InitializeComponent’ method in a new .Net MAUI App project, you can use the «Verify XAML Design Code Behind Link» option. This will ensure that the XAML file is linked to the correct code-behind file.
Here are the steps to do it:
- Open the XAML file causing the error.
- Locate the «x:Class» attribute in the root element of the XAML file.
- Copy the value of the «x:Class» attribute.
- Open the corresponding code-behind file.
- Locate the «namespace» declaration at the top of the code-behind file.
- Ensure that the namespace declared in the code-behind file matches the namespace in the «x:Class» attribute of the XAML file.
- If they don’t match, update the namespace in the code-behind file to match the «x:Class» attribute of the XAML file.
- Save the code-behind file.
- Rebuild the project.
Here is an example of a XAML file with a correct «x:Class» attribute:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyNamespace.MyPage">
<!-- XAML content here -->
</ContentPage>
And here is an example of a code-behind file with a correct namespace declaration:
namespace MyNamespace
{
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
}
}
}
By verifying the XAML Design Code Behind Link, you should be able to fix the ‘InitializeComponent’ build errors in your .Net MAUI App project.
Method 2: Check XAML Design Code Behind File Name
One possible solution to fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in a new .NET MAUI App project is to check the XAML design code behind file name. Here are the steps to do it:
- Open the MainPage.xaml file in your project.
- Check the x:Class attribute in the root element of the XAML file. It should match the name of the code-behind file for that XAML file.
- Open the code-behind file for the MainPage.xaml file (e.g. MainPage.xaml.cs).
- Check the namespace and class name in the code-behind file. They should match the namespace and class name in the XAML file.
- Make sure that the InitializeComponent method is defined in the code-behind file. This method is responsible for initializing the XAML components and must be called in the constructor of the class.
Here is an example of a MainPage.xaml file:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.MainPage">
<StackLayout>
<Label Text="Welcome to .NET MAUI!" />
</StackLayout>
</ContentPage>
Here is an example of a MainPage.xaml.cs file:
using Microsoft.Maui.Controls;
namespace MyApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
}
Make sure that the namespace and class name in the code-behind file match the XAML file, and that the InitializeComponent method is called in the constructor of the class. This should fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in your .NET MAUI App project.
Method 3: Rebuild the Project
To fix the build errors caused by the missing ‘InitializeComponent’ method in a new .Net MAUI App project, you can try rebuilding the project. Here is how to do it:
- Open the Solution Explorer in Visual Studio.
- Right-click on the project that is throwing the build errors and select «Rebuild».
- Wait for the rebuild process to complete.
If the ‘InitializeComponent’ method is still missing after rebuilding the project, you can try the following:
- Clean the project by right-clicking on it in the Solution Explorer and selecting «Clean».
- Rebuild the project by right-clicking on it again and selecting «Rebuild».
- If the ‘InitializeComponent’ method is still missing, try closing and reopening the project or Visual Studio.
Here is an example of how to rebuild a project in C#:
using System;
namespace MyProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
In this example, the ‘Main’ method is the entry point of the program. If the project is not built successfully, the ‘InitializeComponent’ method may be missing, and you can follow the steps above to rebuild the project.
Note that rebuilding the project may not always fix the build errors caused by missing methods or dependencies. In such cases, you may need to troubleshoot the issue further or seek help from other developers or online forums.
Method 4: Clean and Rebuild the Project
To fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in a new .Net MAUI App project, you can try cleaning and rebuilding the project. Here are the steps:
- Open the Solution Explorer in Visual Studio.
- Right-click on the project that is giving the error and select «Clean».
- Wait for the cleaning process to finish.
- Right-click on the project again and select «Rebuild».
- Wait for the rebuilding process to finish.
Here is an example code:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
The InitializeComponent()
method is a generated method that initializes the XAML components in the page. If it cannot be found, it means that the XAML file has not been properly compiled. Cleaning and rebuilding the project can help resolve this issue.
You can also try deleting the bin
and obj
folders in the project directory and then rebuilding the project. This will force Visual Studio to regenerate the files and may help resolve the issue.
That’s it! By following these steps, you should be able to fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in your new .Net MAUI App project.
Method 5: Re-add the XAML Design Code Behind File
To fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in a new .Net MAUI App project, you can try re-adding the XAML Design Code Behind File. Here are the steps to do it:
- Right-click on the project in the Solution Explorer and select Add > New Item.
- Select the «Code» category and then select «Code Behind File».
- Name the file the same name as your XAML file, but with a «.xaml.cs» extension (e.g. «MainPage.xaml.cs» for «MainPage.xaml»).
- Open the newly created code-behind file and add the following code:
using Microsoft.Maui.Controls;
namespace YourNamespace
{
public partial class YourPage : ContentPage
{
public YourPage()
{
InitializeComponent();
}
}
}
- Build the project and the ‘InitializeComponent’ error should be resolved.
Note: Make sure the namespace and class name match the ones in your XAML file.
That’s it! This should fix the ‘The name ‘InitializeComponent’ does not exist in the current context’ build errors in your .Net MAUI App project.