8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Blazor]MatBlazor使ってみた

Last updated at Posted at 2022-04-28

はじめに

Blazor向けのUIフレームワークであるMatBlazorのコンポーネントをいくつか使ってみたので、その備忘録です。
MatBlazorを使えば簡単に見た目をマテリアルデザインにできます。

事前準備

導入は公式サイトのInstallation通りにやれば大丈夫です。
ただ、BlazorのサーバーアプリでMatTableという表のコンポーネントを使用する場合は、こちらのissueにある通り、HttpClientをDIコンテナに登録する必要があります。
以下のように登録しました。
登録の際は、シングルトンでもトラジエントでもなくスコープで登録する必要があるみたいです。
詳しくはこちら

public class Startup
{
	// This method gets called by the runtime. Use this method to add services to the container.
	// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
	public void ConfigureServices(IServiceCollection services)
	{
		// ...
		services.AddScoped<HttpClient>();
	}
}

MatTextField

テキストボックスのコンポーネントです。
@bind-Valueで変数とバインドできます。
typeで入力をテキストや数字などに制限できます。
Label ウォーターマークを指定できます。

<MatTextField type="text" Label="商品名"  @bind-Value="Name" />
<MatTextField type="number" Label="目標割合" @bind-Value="TargetPercentage" />
@code
{
    /// <summary>
    /// 商品名
    /// </summary>
    string Name;

    /// <summary>
    /// 目標割合
    /// </summary>
    int TargetPercentage;
}

以下のように表示できます。
image.png

入力すると、以下のようになります。

image.png

MatSelectItem

ドロップダウンリストのコンポーネントです。
以下はEnumを選択させる例です。
@bind-Valueに選択した要素とバインドする変数を指定できます。
Itemsに選択肢にしたい配列を設定できます。
<ItemTemplate>でどのように選択肢として表示するか指定できます。

<MatSelectItem @bind-Value="AssetClass" 
                Items="Enum.GetValues(typeof(AssetClass)).Cast<AssetClass>().ToArray()">
                <ItemTemplate Context = "assetClass">
                    <span>@GetSelectDisplayName(assetClass)</span>
                </ItemTemplate>
</MatSelectItem>
@code
{
    /// <summary>
    /// アセットクラス
    /// </summary>  
    AssetClassType AssetClass;

    /// <summary>
    /// ドロップダウンリストの選択肢の名前に表示する用の文字列を返す
    /// </summary>
    /// <param name="assetClass">アセットクラス</param>
    /// <returns></returns>
    private string GetSelectDisplayName(AssetClass assetClass)
    {
        return assetClass switch
        {
            AssetClass.Unset=>"選択しない",
            AssetClass.Cash => "現金",
            AssetClass.Commodities => "コモディティ",
            AssetClass.DevelopedCountryBonds => "先進国債券",
            AssetClass.DevelopedStocks => "先進国株式",
            AssetClass.DomesticBonds => "国内債券",
            AssetClass.DomesticStocks => "国内株式",
            AssetClass.EmergingMarketBonds => "新興国債券",
            AssetClass.EmergingMarketsStocks => "新興国株式",
            _ => ""
        };
    }
}

以下のように表示されます。

image.png

MatTable

表のコンポーネントです。
Itemsで表の要素となるコレクションを指定できます。
ShowPagingで表にページング機能を付けれます。
<MatTableHeader>で列の定義ができます。
列幅調整はこちらを参考にしています。cssで指定できるかもしれません。
<MatTableRow>で行の定義ができます。
Itemsに指定したコレクションの一要素をcontextでアクセスすることができます。
MatBlazorを使わず、HTMLのそのままの表を使用した場合は@foreachで要素の数分行を追加する必要がありますが、それは不要です。

以下の例では上記で使ったコンポーネントを組み合わせて表にしています。
シンプルな例は公式ドキュメントを参照ください。

<MatTable Items="@m_AssetInfoCollection.AssetInfos" AllowSelection="true" Striped="false" ShowPaging="false" >
    <MatTableHeader>
        <th><div style="width: 200px">商品名</div></th>
        <th><div style="width: 200px">アセットクラス</div></th>
        <th><div style="width: 200px">評価金額</div></th>
        <th><div style="width: 200px">割合(%)</div></th>
        <th><div style="width: 200px">目標割合(%)</div></th>
    </MatTableHeader>
    <MatTableRow>
        <td><MatTextField type="text" @bind-Value="context.Name" /></td>
        <td>
            <MatSelectItem @bind-Value="context.AssetClass" 
                           Items="Enum.GetValues(typeof(AssetClassType)).Cast<AssetClassType>().ToArray()">
                <ItemTemplate Context = "assetClass">
                    <span>@GetSelectDisplayName(assetClass)</span>
                </ItemTemplate>
            </MatSelectItem>
        </td>
        <td><MatTextField type="number" @bind-Value="context.AppraisedValue" /></td>
        <td>@Math.Round(context.ActualPercentage, 1)</td>
        <td><MatTextField type="number" @bind-Value="context.TargetPercentage" /></td>
    </MatTableRow>
</MatTable>

@code
{
    /// <summary>
    /// アセット情報
    /// </summary>
    private AssetInfoCollection m_AssetInfoCollection = new AssetInfoCollection();

    // ...以下略

}

参考までに、以下に上記で使用しているクラスを記載します。

namespace AssetAllocation_Analysis.Models;

/// <summary>
/// Assetの情報の一覧を表すクラス
/// </summary>
public class AssetInfoCollection
{
  	/// <summary>
	/// アセット情報一覧
	/// </summary>
	public IEnumerable<AssetInfo> AssetInfos => m_AssetInfos;

    // ...以下略
}

/// <summary>
/// Assetの情報を表すクラス
/// </summary>
public class AssetInfo
{
    /// <summary>
	/// 商品名
	/// </summary>
	public string Name { get; set; }

	/// <summary>
	/// アセットクラス
	/// </summary>
	public AssetClassType AssetClass { get; set; }

	/// <summary>
	/// 評価額
	/// </summary>
	public int AppraisedValue { get; set; }

	/// <summary>
	/// 目標の割合
	/// </summary>
	public double TargetPercentage { get; set; }

	/// <summary>
	/// 実際の割合
	/// </summary>
	public double ActualPercentage{ get; set; }

    // ...以下略
}

以下のように表示されます。
image.png

MatButton

ボタンのコンポーネントです。
@onclickでクリック時の操作を指定できます。

<MatButton @onclick="AddButtonOnClick">追加</MatButton>
<MatButton @onclick="UpdateButtonOnClick">更新</MatButton>
@code
{
    private void UpdateButtonOnClick()
    {
        // 更新ボタンクリック時の処理
        // ...以下略
    }

    private void AddButtonOnClick()
    {
        // 追加ボタンクリック時の処理
        // ...以下略
    }
}

以下のように表示されます。
image.png

さいごに

一番有名でコンポーネント数が多いという記事をよく見かけたため使ってみました。
公式ドキュメントが割と充実しているため使いやすいかなと思いました。
MicrosoftのFluentUIというUIフレームワークのBlazor版があるので、それも気になっています。

例が特殊でしたが、これは私が個人的に作ろうとしているアセットアロケーション(どの資産にどの程度の比率で資金を配分するか)を確認するためのアプリから引っ張ってきたためです。。。笑
こちらも公開したらまた記事にしようと思います。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?