c# - 有没有办法在 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; }
}
解决方案
在 Blazor 中,双向绑定包含两个步骤。
- 在渲染过程中,将读取并显示该值。
- 它将订阅组件的更改事件。处理程序会将值写回您的属性。
要让编译器发挥作用,请使用@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。
推荐阅读
- ruby - 循环遍历未知级别的嵌套对象的 DRY 策略
- javascript - 使用 Angular 在 Highcharts 中绘制的数据自己乘以 1000
- swiftui - 未触发 modalView 更改中的 ContentView 重绘
- c++ - 如何在 SFML/C++ 中设置与旋转形状的碰撞
- swiftui - 如何在将相机作为父 SwiftUI 的滚动视图顶部应用不透明度
- c - 使用指针和函数来存储和检索数据的结构
- sql - 根据 SQL Server 中的某些列删除重复记录
- javascript - 带有样式化组件的 Redux 表单
- vega-lite - Vega Lite:带有更多刻度线的符号刻度
- reactjs - React:为什么这些基本数据不会填充到我的功能组件中?