我们可以在Blazor平台中借助typeparam来分配和重用TValue。但是,我们将如何为Blazor InputNumber组件动态分配TValue?
代码示例:
[索引剃刀]
<EditForm>
@*The below definiton is working*@
<InputNumber TValue="int?" @bind-Value="@DynamicModelInstance.ValueAsT"></InputNumber>
@*The below definiton is not working*@
<InputNumber TValue="DynamicModelInstance.Type" @bind-Value="@DynamicModelInstance.ValueAsT"></InputNumber>
</EditForm>
@code {
public DynamicModel<int> DynamicModelInstance { get; set; }
protected override void OnInitialized()
{
DynamicModelInstance = new DynamicModel<int>();
DynamicModelInstance.ValueAsT = 500;
}
}
[DynamicModel.cs]
namespace CustomComponent.Pages
{
public class DynamicModel<T> where T : struct
{
public System.Type Type { get; set; }
public bool Enabled { get; set; }
public DynamicModel()
{
this.Type = typeof(T);
}
private T _value;
public T ValueAsT
{
get { return (T)_value; }
set { this._value = value; }
}
}
}
如何实现这一要求?
问题是您的EditForm:
EditForm需要Model参数或EditContext参数
<EditForm Model="dynamicModelInstance">
<InputNumber @bind-Value="@dynamicModelInstance!.Value" />
</EditForm>
@code {
public DynamicModel<int>? dynamicModelInstance;
protected override void OnInitialized()
{
dynamicModelInstance = new()
{
Value = 500
};
}
}
public class DynamicModel<T> where T : struct
{
public T Value { get; set; }
}