我需要使用一些转换器来修改赋予InputNumber组件的数值。有谁知道如何像使用WPF值转换器一样在绑定过程中修改值?例如,在绑定属性中将给定值除以10(用户输入10 =>属性设置为1,但对用户仍显示为10)?
如果我只想显示百分比(模型属性0.57 =>显示值57%)怎么办?我可以使用某种格式来实现此目的吗?
答案 0 :(得分:1)
@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;
}
}
}
答案 1 :(得分:0)
因此,扩大@Zsolt Bendes的答案是:我认为转换应在视图级别进行。模型不应该知道视图的实现(例如,模型中的百分比值属性在0 ... 1范围内)。我认为最好在代码后面(或@code块)上实现这些附加属性以充当转换器。如果您有多个属性需要转换为例如百分比值,但我还没有发现更好的方法。所以我建议的代码是(带有局部类):
<EditForm Model="@Example" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="row">
<label for="prop">Property as percentage:</label>
<InputNumber id="prop" @bind-Value=PercentageProperty/>
<p>%</p>
</div>
<button type="submit">Submit</button>
</EditForm>
public partial class Component : ComponentBase
{
public ExampleModel Example { get; set; }
public double PercentageProperty { get => Example.ModelProperty * 100; set => Example.ModelProperty = value / 100; }
public void HandleValidSubmit()
{
// Code to handle submit
}
}
public class ExampleModel
{
public double ModelProperty { get; set; }
}
希望Blazor团队设法使InputNumber组件绑定能够处理委托,或通过其他某种方式来处理可重用的转换器...