首页 > 解决方案 > 有没有办法在 blazor inputtext 中动态进行双向绑定

问题描述

我正在尝试创建一个可重用的控件。我已经想出了如何使用反射来处理只读场景@typeof(TItem).GetProperty(col.PropertyName).GetValue(item)

现在我想对双向绑定做同样的事情<InputText @bind-Value="item.{select a property using the PropertyName value in ColumnDefinition}</InputText>"

有没有办法使用字符串选择项目的属性?

谢谢!

更多参考如下:

@typeparam TItem
<EditForm>
    <table>
        <thead>
            <tr>
                <Virtualize Items="ColumnDefinitions" Context="col">
                    <th>
                        @col.Caption
                    </th>
                </Virtualize>
            </tr>
        </thead>
        <tbody>
            <Virtualize Items="Items" Context="item">
                <tr>
                    <Virtualize Items="ColumnDefinitions" Context="col">
                        <td>
                            @typeof(TItem).GetProperty(col.PropertyName).GetValue(item)
                            <InputText @bind-Value=""></InputText>
                        </td>
                    </Virtualize>
                </tr>
            </Virtualize>
        </tbody>
    </table>
</EditForm>


@code {
    [Parameter] public List<ColumnDefinition> ColumnDefinitions { get; set; }
    [Parameter] public List<TItem> Items { get; set; }
}

    public class ColumnDefinition
    {
        public short Order { get; set; }
        public string Caption { get; set; }
        public bool IsReadOnly { get; set; } = true;
        public InputTypeEnum InputType { get; set; } = InputTypeEnum.Text;
        public string PropertyName { get; set; }
    }

标签: c#htmlasp.net-coreblazor

解决方案


在 Blazor 中,双向绑定包含两个步骤。

  1. 在渲染过程中,将读取并显示该值。
  2. 它将订阅组件的更改事件。处理程序会将值写回您的属性。

要让编译器发挥作用,请使用@bind-Value而不是Value. 但是,您可以通过自己设置事件处理程序来“破解”系统。

<InputText 
   Value="@typeof(TItem).GetProperty(col.PropertyName).GetValue(item)" 
   ValueChanged="@(e => typeof(TItem).GetProperty(col.PropertyName).SetValue(item,e))">
</InputText>

作为参考,请查看https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-5.0


推荐阅读