我有一个剃刀组件库,其中我正在创建自定义的可重用组件。我有一个“ContentItem”组件,希望能够简单地绑定组件中对象的属性,然后使用反射或其他方法来发现必要的信息。例如:
ContentItem.razor
ContentItem.razor
<div>
<div>@DisplayName</div>
<div>@PropertyValue</div>
</div>
ContentItem.razor.cs
public partial class ContentItem
{
/// <summary>
/// The property that this component will bind to
/// </summary>
[Parameter]
public **???** ObjectProperty{ get; set; }
public string DisplayName;
public string PropertyValue;
protected override void OnParametersSet()
{
try
{
DisplayName = //reflection or some way to get the display attribute from the Object Property
PropertyValue = //reflection or inspection of the ObjectProperty
base.OnParametersSet();
}
catch (Exception ex)
{
throw new exception("Error", ex);
}
}
客户端应用程序页面
<div>
<ContentItem ObjectProperty="@User.FirstName" />
</div>
实际上,当你使用 "ContentItem" 组件时,你只需要传递 ObjectProperty,然后 "ContentItem" 组件将执行某种反射和/或检查该参数以按预期渲染 HTML 的操作。