Program Tip

Xamarin.Forms-새 페이지를 만들 때 InitializeComponent가 존재하지 않습니다.

programtip 2020. 11. 19. 21:54
반응형

Xamarin.Forms-새 페이지를 만들 때 InitializeComponent가 존재하지 않습니다.


Visual Studio를 사용하여 Xamarin.Forms를 사용해보고 있습니다. 가이드를 따르려고합니다 : http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/getting_started_with_xaml/

간단히 말해서, PCL을 사용하여 Xamarin.Forms 솔루션을 만든 다음 Forms XAML PagePCL 프로젝트 에 추가하려고합니다 .

생성되는 코드 숨김은 다음과 같습니다.

    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent(); 
        }
    }

여기서 문제 InitializeComponent();는 빨간색입니다. 빌드하려고 할 때The name 'InitializeComponent' does not exist in the current context

나는 해결책을 찾고 있었고 다른 사람들이 같은 문제를 겪었지만 그들의 해결책은 나를 위해 작동하지 않을 것입니다. 다음은 내가 사용하려고 한 제안입니다. http://blog.falafel.com/xamarin-error-initializecomponent-does-not-exist-in-the-current-context/

이 문제에 대한 해결책이 있으면 알려주십시오. 감사!

최신 정보:

내 PCL (내 XAML 페이지도 추가하려는 위치)에는 다음이 포함됩니다.

App.cs :

    public class App : Application
    {
        public App()
        {
            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        new Label {
                            XAlign = TextAlignment.Center,
                            Text = "Welcome to Xamarin Forms!"
                        }
                    }
                }
            };
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

그리고 내 XAML 페이지 :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamaTest.MyXamlPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

코드 숨김 :

    public partial class MyXamlPage : ContentPage
    {
        public MyXamlPage()
        {
            InitializeComponent();
        }
    }

업데이트 : 이 오류는 일반적으로 VS 2015에 나타나지 않습니다. 그렇다면 원래 대답은 다음과 같습니다.

해결책을 찾았습니다! .XAML 파일을 마우스 오른쪽 버튼으로 클릭하고 속성을 선택 합니다.

Custom Tool 이라는 속성이 표시됩니다 . 값을에서 MSBuild:Compile변경MSBuild:UpdateDesignTimeXaml

이것은 문제를 해결할 것입니다. 반대표에 대해 모르지만 다음은 내 스크린 샷입니다.

스크린 샷 최신 정보:

드물게 다시 나타납니다. 그렇다면 Xaml과 파일 숨김 파일을 열고 저장하십시오. 나는 그것이 최선의 해결책이 아니라는 것을 압니다.


나는 때때로 이것을 얻고 여기에 지금까지 그들을 해결 한 체크리스트가 있습니다.

  1. .xaml 및 .xaml.cs의 네임 스페이스가 일치하는지 확인

  2. 올바른 부모-페이지의 경우 ContentPage 및 컨트롤의 경우 ContentView에서 상속

  3. .xaml 파일의 빌드 동작을 Embedded Resource공유 프로젝트의 경우로 설정합니다.


내 관찰에 관한 한 Visual Studio 2015에서 XAML 속성은 기본적으로 여기에서 투표가 많은 답변에서 제안한대로 이미 설정되어 있습니다.

  • 맞춤 도구 = MSBuild:UpdateDesignTimeXaml
  • 빌드 액션 = Embedded Resource

그러나 오류는 여전히 가끔 나타납니다 ... ( 이 다른 질문 에서와 같이 ).

해당 XAML 파일을 편집 한 다음 CTRL+ 를 누르면 S정상적으로 작동하지만 그럴 필요는 없습니다. 사용자 지정 도구를 강제로 실행하는 더 깨끗한 방법은 XAML 파일을 마우스 오른쪽 단추로 클릭 한 다음 "사용자 지정 도구 실행"상황에 맞는 메뉴를 클릭하는 것입니다.

여기에 이미지 설명 입력


나는이 문제를 만났다. VS의 XAML 파일 인코딩과 관련이 있습니다. VS2015를 사용하고 있습니다.

이 문제를 다음과 같이 해결했습니다.

  1. 프로젝트에서 * .xaml 파일을 열고 저장 버튼을 클릭합니다. (VS2015에서 올바른 인코딩이 적용됩니다).

  2. 그런 다음 프로젝트를 다시 열고 다시 빌드하십시오. 이제 오류가 없습니다.


Xamarin.Forms NuGet 패키지를 업데이트하면 작업을 수행해야합니다.


이것은 아마도 귀하의 경우가 아니지만 비슷한 문제가 있었고 내 이름이 일치하지 않는 xaml 및 코드였습니다. 예를 들어 샘플에 따르면 네임 스페이스 뒤에있는 코드가 XamaTest (대부분의 경우 앱 이름)이고 클래스가 MyXamlPage 인 경우 xaml 클래스 이름은 XamaTest.MyXamlPage ([namespace]. [classname]) 여야합니다.

코드가 포함 된 빈 xaml을 만든 후 바보 같았고 xaml에서 클래스 이름을 변경했는데이 오류가 발생했습니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamaTest.MyXamlPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

코드 숨김 :

public partial class MyXamlPage : ContentPage

xaml 페이지에 ax : Name = "..."을 추가해보십시오 ... 다른 것은 나에게 효과가 없었습니다.하지만 페이지의 일부 요소에 x : Name 속성을 추가 한 후 오류가 사라졌습니다 (대부분-I 여전히 가끔 얻습니다). Xamarin.Forms의 최신 빌드 (1.5.0.6447)를 사용합니다.

XAML은 공유 프로젝트에서 작동하지 않으며 이식 가능한 프로젝트에서만 작동합니다.


blah.xaml.g.cs실제로 파일 의 (재생) 생성 이 문제인 것 같습니다. 나는 공유 프로젝트에서 이것을 많이 얻습니다 (이것이 다른 선택의 여지가 없으면 사용하지 않는 이유입니다). 어떤 이유로 든 Visual Studio보다 Xamarin Studio에서 더 많이 발생합니다. XS를 전혀 사용하지 않으려 고합니다.

종종 다른 플랫폼 중 하나를 언로드하고 (예 : droid를 빌드하는 경우 ios를 언로드) 정리하고 다시 빌드하면 문제가 해결됩니다.

문제가되는 .xaml파일 중 하나를 열고 일부 xaml 마크 업을 변경 하는 것과 같은 작업을 시도 할 수도 있습니다 (예 : x:Name컨트롤 또는보기 중 하나에를 추가하거나 변경 ). 이것은 xaml.g.cs 파일의 재생성을 강제하고 (적어도 나를 위해) 일반적으로 문제를 해결합니다.

이것은 정말로 일이되어서는 안됩니다.


이 오류는 다음과 같습니다.

  1. 나는 제거 ContentPage-cs+xaml하고, App-cs+xaml실제로 삭제하지 않고 프로젝트를.
  2. 다른 폴더의 프로젝트에 다시 추가했습니다.

이것은 수정되었습니다;

  1. .xaml문제가있는 클래스 파일을 선택하십시오 .
  2. 마우스 오른쪽 버튼을 클릭하고을 선택 properties합니다.
  3. 에서 Build action선택 "포함 리소스"
  4. 에서 Custom Tool유형 "은 MSBuild : UpdateDesignTimeXaml"
  5. 청소하고 빌드하면 사라졌습니다.

Xamarin.Forms 페이지에서 InitializeComponent와 같은 intellisense 오류가 발생하지만 프로젝트가 실제로 제대로 빌드되고 실행되는 경우 마법사를 사용하여 새 Forms 페이지를 추가하여 모든 오류를 수정합니다.

그런 다음 새 페이지를 삭제할 수 있습니다.


페이지 텍스트를 확인하십시오 x:Class="AppName.Page1". AppName 은 앱 이름이어야합니다.


  • Visual Studio 2013업데이트 4 환경 에서 비슷한 문제가 있었고 웹에서 찾은 모든 권장 사항을 시도했습니다. 내 문제가 해결되지 않았습니다.
  • 그런 다음 해결 방법을 시도했습니다. Visual Studio 2015미리보기를 설치 하고 xamarin 양식 프로젝트로 새 빈 앱을 만듭니다 .
  • Xaml파일을 추가했을 때 모든 것이 정상이며 InitialComponent방법 문제가 사라졌습니다.
  • 문제의 원인이 정확히 어디에 있는지는 모르지만 구성 설정과 관련된 문제인 것 같습니다.

Clean and rebuild가 나를 위해 트릭을했습니다!


* .xaml을 마우스 오른쪽 단추로 클릭하고 속성을 클릭 한 다음 "사용자 지정 도구"값을 "MSBuild : UpdateDesignTimeXaml"로 변경 한 다음 "Build Action"속성을 " Embedded Resource "로 변경하면 빌드 프로젝트가 작동합니다.


나를 위해 일한 매우 간단한 솔루션 :

  • xaml / cs 파일의 내용 복사
  • xaml / cs 파일 삭제
  • 새 수업을 만들고 내용을 붙여 넣습니다.

이제 InitializeComponent () 함수가 빨간색 밑줄없이 나타납니다.

이것이 누군가를 돕기를 바랍니다.


이 문제는 솔루션 프로젝트가 "Xamarin.Forms.Core", "Xamarin.Forms.Xaml"및 "Xamarin.Forms.Platform"버전 1.0.0.0의 1.4.0.0 버전을 참조 할 때 나타납니다.

이 문제를 해결하려면 1.3.3.0 버전의 dll로 다운 그레이드해야했지만이 버전에서는 Xamarin.Forms.Platform 1.0.0.0이 존재하지 않습니다.


프로젝트에서 참조하는 Xamarin.Forms 패키지의 버전을 확인합니다.

.csproj 파일 Xamarin.Forms 너겟 패키지


나는 때때로 같은 문제를 겪어 왔고 이것이 내가 그것을 고치기 위해해온 일이다. PCL 프로젝트에서 나는 새로운 크로스 플랫폼 XAML 페이지를 프로젝트에 추가한다. 새 XAML 페이지를 추가하면 "후크"에 대한 참조가 몇 초 정도 걸립니다. 새 XAML 페이지가 프로젝트에 성공적으로 추가되면 문제가있는 XAML 페이지의 빨간색 밑줄이 지워집니다. 문제가 해결되면 방금 추가 한 XAML 파일을 삭제하기 만하면됩니다. -요약하면 새 XAML 페이지를 추가 한 다음 삭제하면 문제가 해결되었습니다.


나는 방금 모든 패키지를 업데이트 했으며 잘 작동합니다.


Change Page properties to :

BuildAction => Embedded resource 
CustomTools => MSBuild:UpdateDesignTimeXaml

I had a caching issue when I encountered this error.

To get this fixed, simply uninstall last version of Xamarin.Forms package and reinstall a previous working version.

When the rebuild is successful, then update the package again to the latest version.


Check the class name properly.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="{AppName}.{ClassName}">
</ContentPage>

The class name should be a combination of App name and partial class name


In my case the problem was the project path. The generated code file gets a name including the absolute path encoded to make it a valid filename. The path was "D:\Projekt C#\ProjectRootFolder\Project". The filename generated by the build tool was "Project.Droid.D_.Projekt_C_. Namespace etc." Moving the project to a path like "D:\project\ProjectRootFolder" helped in my case.


I'm using Visual Studio 2015, I got the same problem, and found none of the answers on the net was a full solution. Here I'll explain what worked for me.

My primary goal here was to eliminate the red error message that kept coming up

The name InitializeComponent does not exist in the current context

Basically I created a function called InitializeComponent2() that does exactly the same thing as InitializeComponent() and used that instead, I literally copied the code for InitializeComponent(). Does the job.

It looks like this (and I'll explain):

[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private void InitializeComponent2()
{
    // Change to:
    //   this.LoadFromXaml(typeof(Page2)); // for Page2
    //   this.LoadFromXaml(typeof(Page3)); // for Page3
    // and put
    //   using Xamarin.Forms.Xaml;
    // at the top of each source file.
    this.LoadFromXaml(typeof(Page1));
}

Put the function in the definition of each of your pages (.cs files) e.g.

public partial class Page1 : ContentPage
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private void InitializeComponent2()
    {
        // Change to:
        //   this.LoadFromXaml(typeof(Page2)); // for Page2
        //   this.LoadFromXaml(typeof(Page3)); // for Page3
        // and put 
        //   using Xamarin.Forms.Xaml; 
        // at the top of each source file.
        this.LoadFromXaml(typeof(Page1));
    }
}

Also you need to put using Xamarin.Forms.Xaml; at the top of each .cs page where LoadFromXaml(..) is used.

And then of course change InitializeComponent() to InitializeComponent2() to call the new function. i.e. you have put the function into the same context as the page making the error go away. I can't imagine the real InitializeComponent function will get anything added to it as you modify your project but that is a possibility. It's been fine for me so far.

I tried many things, changing the Build Action, the XAML namespace, restarting vs, cleaning+rebuilding, looking for NuGet package updates.

Basically, Visual Studio compiled and ran the program fine on my android device + emulator, but that error message wouldn't go away. My solution is for Android, but it may also work for iOS etc.

I went back to the root of the problem InitializeComponent() The actual code for this function is generated in a file called <Your Project Name>.Page1.xaml.g.cs or Page2.xaml.g.cs for example. However, it (the file) is only generated when a certain event gets fired. I was lucky to discover it by typing text into "Custom Tool Namespace", which fired that event, for one of the xaml pages(a file ending in .xaml, not .cs - make sure you have .xaml file selected), type some text and press enter and the file will be created.

Then I had the great idea of making InitializeComponent2(), a function exactly the same as InitializeComponent() and putting it in each cs file so it exists without having to generate the .xaml.g.cs every time you want the error to go away.


I don't know if this is solved, but for me, the only thing I had to do is remove the first line of the XAML ("xml version="1.0" encoding="utf-8")

Sometimes source version control, tries to identify which type of file is and add this kind of stuff.


add using Xamarin.Forms.Xaml

tested on Visual Studio 2017


  1. Select the App.xaml and MainPage.xaml file of the class in which the issue is present.
  2. Right click and select properties.
  3. In Build action select "Embedded Resource"
  4. In Custom Tool type "MSBuild:UpdateDesignTimeXaml"
  5. Clean and Build and it was gone.

Ultimate solution would be to edit the project file in a text editor and just copy the pattern from another non-conflicting file. This solution worked for me. Usually, you would look for this syntax:

<Compile Update="Your\Path\YourContentPage.xaml.cs">
  <DependentUpon>YourContentPage.xaml</DependentUpon>
</Compile>

Xaml 페이지 속성
Build Action = Embedded resource
에서는 Visual Studio 2017 에서만 작동합니다.


위의 모든 것을 시도했지만 운이 없었습니다. 저에게 효과가 있었던 것은 Xamarin.Forms 패키지를 강제로 다시 설치하는 것입니다. 패키지 관리자 콘솔 프롬프트에서;

업데이트 패키지 xamarin.forms-재설치

패키지를 업데이트하지 않고 제거하고 다시 추가합니다.

참고 URL : https://stackoverflow.com/questions/28818525/xamarin-forms-initializecomponent-doesnt-exist-when-creating-a-new-page

반응형