首页 > 解决方案 > 类属性的 TypeConverter 用法

问题描述

我有一个类EntityItemValue,它的属性名为Valuetype object,实际类型可以通过位于类Type内部的属性来确定EntityItem

public class EntityItemValue
{        
    public EntityItem Item { get; set; }
    public object Value { get; set; }
    // other properties ...
}

public class EntityItem
{        
    public Type Type
    // other properties ...
}

现在我想像Value下面这样绑定 Blazor 组件中的属性。

<div class="flex-container">
    <div class="input-style"><input type="text" @bind="@Param.Value" /></div>
</div>

@code {
    [Parameter]
    public EntityItemValue Param { get; set; }
}

但得到这个例外:

类型“System.Object”没有支持从字符串转换的关联 TypeConverter。将“TypeConverterAttribute”应用于类型以注册转换器。

我了解这里的问题是什么,但是如何根据类中的属性TypeConverter正确使用任何实现想法或更好的建议来解决这个问题?TypeEntityItem

标签: c#asp.net-coreblazor

解决方案


由于<input>元素只绑定到字符串 - 我们可以在设置参数时首先检查:

protected override void OnParametersSet()
{
    if (Param.Item.Type != typeof(string))
    {
        throw new InvalidOperationException("Cannot bind a non string to a string input");
    }
}

现在我们有了这个,我们可以将其包装objectstring

private string Value
{
    get => (string)Param.Value;
    set => Param.Value = value;
}

最后更新输入以绑定到我们的字符串

<input type="text" @bind="@Value" />

推荐阅读