首页 > 解决方案 > Blazor 中的 InputNumber 绑定转换器

问题描述

我需要使用一些转换器来修改给 InputNumber 组件的数值。有谁知道如何以与 WPF 值转换器相同的方式修改绑定过程中的值?例如,在绑定属性中将给定值除以 10(用户输入 10 => 属性设置为 1,但仍向用户显示为 10)?

如果我只想显示百分比(模型属性 0.57 => 显示值 57 %)怎么办?我可以使用某种格式化方式来实现这一点吗?

标签: blazorconverters

解决方案


@Jazb 评论示例

<EditForm Model="@exampleModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputNumber id="name" @bind-Value="exampleModel.PropertyAsInt" />
    <InputNumber @bind-Value="exampleModel.PropertyAsDouble" />

    <button type="submit">Submit</button>
</EditForm>

@code {
     private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine(exampleModel.GetFormattedIntProperty);
        Console.WriteLine($"{exampleModel.GetFormattedDouble}%");
    }
}

该模型:

public class ExampleModel
    {
        public int PropertyAsInt { get; set; } = 10;
        public double PropertyAsDouble { get; set; } = 57;

        public int GetFormattedIntProperty
        {
            get
            {
                return int.Parse(PropertyAsInt.ToString()[0..1]);
            }
        }

        public double GetFormattedDouble
        {
            get
            {
                return PropertyAsDouble / 100;
            }
        }
    }

推荐阅读