Blazor 自定义可重用基础组件之 MyInputNumber(InputNumber)

news/2024/11/7 18:03:35/

只能输入数字的输入框,为避免命名冲突,先命名为MyInputNumber。

MyInputNumber.razor

@inherits InputBase<TValue>
@typeparam TValue
<div class="d-flex"><label class="control-label w-auto mt-2"><b>@Lable</b></label><div style="width:@InputWidth"><input type="number" @bind-value="CurrentValue" class="form-control" disabled="@Disabled" @ref="Element" /><span class="w-100"><ValidationMessage For="ValueExpression" /></span></div>
</div>

MyInputNumber.razor.cs

    public partial class MyInputNumber<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase<TValue>{[Parameter]public required string Lable { get; set; }[Parameter]public string InputWidth { get; set; } = "300";[Parameter]public bool Disabled { get; set; }protected override void OnParametersSet(){base.OnParametersSet();Lable += ":";InputWidth += "px;";}//以下是复制于InputNumber 的源码,除了渲染部分注释掉外未作改动。private static readonly string _stepAttributeValue = GetStepAttributeValue();private static string GetStepAttributeValue(){// Unwrap Nullable<T>, because InputBase already deals with the Nullable aspect// of it for us. We will only get asked to parse the T for nonempty inputs.var targetType = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);if (targetType == typeof(int) ||targetType == typeof(long) ||targetType == typeof(short) ||targetType == typeof(float) ||targetType == typeof(double) ||targetType == typeof(decimal)){return "any";}else{throw new InvalidOperationException($"The type '{targetType}' is not a supported numeric type.");}}/// <summary>/// Gets or sets the error message used when displaying an a parsing error./// </summary>[Parameter] public string ParsingErrorMessage { get; set; } = "The {0} field must be a number.";/// <summary>/// Gets or sets the associated <see cref="ElementReference"/>./// <para>/// May be <see langword="null"/> if accessed before the component is rendered./// </para>/// </summary>[DisallowNull] public ElementReference? Element { get; protected set; }//这里是生成渲染树,我们用MyInputNumber.razor代替了。/// <inheritdoc />//protected override void BuildRenderTree(RenderTreeBuilder builder)//{//    builder.OpenElement(0, "input");//    builder.AddAttribute(1, "step", _stepAttributeValue);//    builder.AddMultipleAttributes(2, AdditionalAttributes);//    builder.AddAttribute(3, "type", "number");//    builder.AddAttributeIfNotNullOrEmpty(4, "name", NameAttributeValue);//    builder.AddAttributeIfNotNullOrEmpty(5, "class", CssClass);//    builder.AddAttribute(6, "value", CurrentValueAsString);//    builder.AddAttribute(7, "onchange", EventCallback.Factory.CreateBinder<string?>(this, __value => CurrentValueAsString = __value, CurrentValueAsString));//    builder.SetUpdatesAttributeName("value");//    builder.AddElementReferenceCapture(8, __inputReference => Element = __inputReference);//    builder.CloseElement();//}/// <inheritdoc />protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage){if (BindConverter.TryConvertTo<TValue>(value, CultureInfo.InvariantCulture, out result)){validationErrorMessage = null;return true;}else{validationErrorMessage = string.Format(CultureInfo.InvariantCulture, ParsingErrorMessage, DisplayName ?? FieldIdentifier.FieldName);return false;}}/// <summary>/// Formats the value as a string. Derived classes can override this to determine the formatting used for <c>CurrentValueAsString</c>./// </summary>/// <param name="value">The value to format.</param>/// <returns>A string representation of the value.</returns>protected override string? FormatValueAsString(TValue? value){// Avoiding a cast to IFormattable to avoid boxing.switch (value){case null:return null;case int @int:return BindConverter.FormatValue(@int, CultureInfo.InvariantCulture);case long @long:return BindConverter.FormatValue(@long, CultureInfo.InvariantCulture);case short @short:return BindConverter.FormatValue(@short, CultureInfo.InvariantCulture);case float @float:return BindConverter.FormatValue(@float, CultureInfo.InvariantCulture);case double @double:return BindConverter.FormatValue(@double, CultureInfo.InvariantCulture);case decimal @decimal:return BindConverter.FormatValue(@decimal, CultureInfo.InvariantCulture);default:throw new InvalidOperationException($"Unsupported type {value.GetType()}");}}}

使用:

<EditForm Model="MyNumber1">
<p><MyInputNumber Lable="数字测试" @bind-Value="MyNumber1.MyNumber1" InputWidth="300" ParsingErrorMessage="这里只能输入数字!" /></p>
</EditForm>
@code{private MyNumber MyNumber1 = new();internal class MyNumber{internal int MyNumber1 { get; set; }}
}//其中加不加 TValue="int"好像都行

效果:


http://www.ppmy.cn/news/709643.html

相关文章

【数据库】某个表有近千万数据,CRUD比较慢,如何优化?

某个表有近千万数据&#xff0c;CRUD比较慢&#xff0c;如何优化&#xff1f; 优化之前我们先思考一下下面的问题&#xff1a; 思考 如何设计或优化千万级别的大表&#xff1f;此外无其他信息&#xff0c;个人觉得这个话题有点范&#xff0c;就只好简单说下该如何做&#xf…

Bruce Schneier 和他的密码学以及网络安全经典著作推荐

经典语录-- 数学是完美的&#xff0c;而现实却是主观的。数学是精确的&#xff0c;而计算机却充满矛盾。数学是遵循逻辑的&#xff0c;而人却是不稳定的、反复无常的&#xff0c;甚至是难以理解的。 密码学是数学的一个分支。像所有其他数学分支一样&#xff0c;它涉及的是数…

微信开发中消息回复的代码_消息中的消息

微信开发中消息回复的代码 Steganography / stegəˈngrəfi / (noun): the practice of concealing messages or information within other nonsecret text or data. 文字/名词&#xff1a;在其他非秘密文本或数据中隐藏消息或信息的做法。 Synopsis: it’s possible to effe…

本周AI热点回顾:GPT-3开始探索付费使用;这个视频「橡皮擦」让你瞬间消失;英伟达最强消费级显卡RTX 3090出炉

点击左上方蓝字关注我们 01 服贸会来了&#xff01;百度飞桨发布最新成果&#xff0c;获“科技创新服务示范案例” 这周末要被“黑科技”十足的服贸会承包了&#xff01;今年服贸会以“科技办会”的理念&#xff0c;展示了人工智能、5G、增强现实和虚拟现实等最新的科技成果。本…

SpringBoot 实现合并表头导出数据 - EasyExcel应用

文章目录 1. 构建实体类2. 导出3. 导入 EasyExcel是一款开源的Java处理Excel文件的工具库&#xff0c;它提供了简单易用的API&#xff0c;可以方便地读取、写入和操作Excel文件。下面是一些常见的EasyExcel应用场景&#xff1a; 读取Excel文件&#xff1a;使用EasyExcel可以轻…

MindSpore基础知识【深度学习、基础】

MindSpore是什么&#xff1f;它与其他深度学习框架有什么不同之处&#xff1f; MindSpore是华为推出的一款开源深度学习框架。它提供了一套端到端的开发工具和算法库&#xff0c;旨在简化深度学习模型的开发、训练和部署过程。 与其他深度学习框架相比&#xff0c;MindSpore有…

ARM day5 (点灯实验 汇编C)

汇编 .text .global _start _start: /**********LED1点灯**************//**********RCC草节初始化**************///1.通过RCC_MP_AHB4ENSETR寄存器使能GPIOE组控制器0x50000A28[4] 1ldr r0,0x50000A28ldr r1,[r0]orr r1,r1,#(0x1 << 4)str r1,[r0]//1.通过RCC_MP_AH…

web安全php基础_php变量命名及其作用域

php变量命名规则 php变量命名规则 变量以 $ 符号开始&#xff0c;后面跟着变量的名称变量名必须以字母或者下划线字符开始变量名只能包含字母数字字符以及下划线&#xff08;A-z、0-9 和 _ &#xff09;变量名不能包含空格变量名是区分大小写的&#xff08;$y 和 $Y 是两个不…