1

我是 Blazor 的新手,而且总的来说是 C#,但我正在查看 Blazorise UI 包并注意到当你想为按钮提供“颜色”属性时,它会强制你使用类似 Color="Color.Primary" 的东西或颜色 =“颜色。警告”。我如何在我自己的剃须刀组件中实现这一点?

使用razor Button组件的随机组件

<Button @onclick="TestClick2" Color="BtnColor.Danger">Test 3</Button> <--- Color parameter is not working here. It just uses the literal string of 'BtnColor.Danger' instead of 'danger'

Button.razor

<button class="btn @_btnColorClass">
    @ChildContent
</button>

Button.razor.cs

using Microsoft.AspNetCore.Components;
using System.Collections.Generic;

namespace BlazorServer.UI.Buttons
{
    public partial class Button : ComponentBase
    {
        private string _btnColorClass;
        public static class BtnColor
        {
            public const string Primary = "primary";
            public const string Secondary = "secondary";
            public const string Danger = "danger";
        }

        [Parameter]
        public RenderFragment ChildContent { get; set; }

        [Parameter(CaptureUnmatchedValues = true)]
        public Dictionary<string, object> AdditionalAttributes { get; set; }

        [Parameter]
        public string Color { get; set; } = BtnColor.Primary;   <------- here?!?

        protected override void OnInitialized()
        {
            _btnColorClass = $"btn-{ Color }";
        }

    }
}
4

3 回答 3

0
public enum Color
    {
        Primary,
        Secondary,
        Danger
    }

public static class ColorExtensions
    {
        public static string GetString(this Color me)
        {
            switch (me)
            {
                case Color.Primary:
                    return "Primary";
                case Color.Secondary:
                    return "Secondary";
                case Color.Danger:
                    return "Danger";
                default:
                    return "";
            }
        }
    }

用法:

Color color = Color.Primary;
string output = color.GetString();
于 2022-01-25T16:42:05.720 回答
0

如果要将参数保留为字符串(这意味着您可以使用预定义的条目或编写自己的条目),请使用常量。

public static class BtnColor
{
    public const string Primary = "Primary";
    // ...
}

您还可以更改参数以使用枚举而不是字符串。

[Parameter]
public BtnColor Color { get; set; } = BtnColor.Primary;
public enum BtnColor
{
    Primary,
    // ...
}
于 2022-01-24T22:04:43.080 回答
0
css classes:
    .primary{}
    .secondary{}
    .danger{}
    
color enum:
    public enum Color{ Primary, Secondary, Danger}

Parameter:
[Parameter]
public Color Color { get; set; } = Color.Primary;

html:
<button class="@Color.ToString().ToLower()">@childcontent</button>
于 2022-01-25T15:05:36.893 回答