【问题标题】:Moving Blazor code to code-behind - simple example将 Blazor 代码移动到代码隐藏 - 简单示例
【发布时间】:2020-08-28 13:38:25
【问题描述】:

我刚开始阅读 Blazor 教程,并试图掌握代码。我有一个看起来像这样的剃须刀页面(来自教程):

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<!--
    This has been moved to the code-behind.
@code {
    private int currentCount = 0;

    private void IncrementCount() {
        currentCount++;
    }
}
-->

后面的代码给了我几个错误,说 Counter 已经定义并且 IncrementCount 已经存在。我的代码如下所示:

using Microsoft.AspNetCore.Components;

namespace BlazorApp8.Pages {

    public partial class CounterCode : ComponentBase {

        protected int currentCount = 0;

        protected void IncrementCount () {
            currentCount++;
        }


    }

}

我知道我做错了一些简单的事情,但不确定是什么。有人可以帮忙吗?

【问题讨论】:

  • 为什么需要分部类?
  • 我没有。那是我试图弄清楚我在做什么。我刚刚遗漏了一行代码(请参阅下面的答案)。

标签: blazor code-behind


【解决方案1】:

我明白了。在您的客户端代码中,您必须从您的类继承,如下所示:

@inherits CounterCode   <!-- This is what I missed -->
@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

【讨论】:

  • 嗨,布赖恩,请稍后查看;部分类方法可以很好地工作,但是如果您进入通用组件和更复杂的场景,您可能会遇到一些问题。在这些情况下,设置一个基类作为后面的代码(不是部分代码),然后在 razor 文件中继承该基类。希望这会有所帮助,祝你好运!
  • 好消息。谢谢,尼克!这是新的和令人兴奋的。
【解决方案2】:

我更喜欢另一种创建代码隐藏文件的方式。

在同一目录中创建一个新的类文件 Counter.razor.cs。将部分添加到类中。完成!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2012-05-19
    • 2011-04-06
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多