问题
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