How to create “Code Behind” Blazor Components with VS 2019?

自作多情 提交于 2020-06-15 07:06:09

问题


I can create an inline component like

<h1>@foo</h1>

@functions {

    string foo = "foo";
}

However when I create Foo.razor containing just:

<h1>@foo</h1>

And Foo.razor.cs containing:

namespace MyApp.Client.Components {
    public class Foo: ComponentBase {

        public string foo;
    }
}

I get:

Error   CS0101  The namespace 'MyApp.Client.Components' already contains a definition for 'Foo'

I am using the latest VS 2019 and Blazor libraries.

What am I doing wrong?


回答1:


Currently, the "code-behind" and .razor view can't share the same name.

So when you have Foo.razor.cs and Foo.razor it is seen as the same file and thus causes a collision.

Workaround for now: Rename your Foo.razor.cs to FooBase.cs (or something else).

Then in your Foo.razor, add @inherits FooBase

There is a GitHub issue regarding this here: https://github.com/aspnet/AspNetCore/issues/5487




回答2:


Since October 2019, it is possible to use partial classes. So today you can name the class in the code-behind file like this:

public partial class Foo : ComponentBase
{
    protected override Task OnInitializedAsync()
    {
        // do stuff
    }
}


来源:https://stackoverflow.com/questions/56111322/how-to-create-code-behind-blazor-components-with-vs-2019

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!