shuhelohelo’s blog

Xamarin.Forms多めです.

Blazorでコードビハインド的な書き方

コードビハインド的な書き方

  • ロジック部分を別ファイル、別クラスに記述しておく。
  • そのクラスはComponentBaseクラスを継承しておく。
  • Razorファイルから利用するプロパティやメソッドはpublicにしておく。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;

namespace Blazor.ViewModels
{
    public class IndexViewModel : ComponentBase
    {
        public string greeting { get; set; } = "Hello, world!";
        public string currentDateTime { get; set; } = "???";

        public void GetDateTime()
        {
            this.currentDateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
        }

    }
}
  • Razorファイル側ではそのクラスへの参照を記述する。@inheritsディレクティブを使って。
@page "/"
@inherits Blazor.ViewModels.IndexViewModel

<h1>@greeting</h1>

Welcome to your new app.

@*<SurveyPrompt Title="How is Blazor working for you?" />*@

<Counter IncrementAmount="10" />
<FetchData />

<button class="btn btn-primary" onclick="@GetDateTime">Get Current Time</button>
<label>@currentDateTime</label>