[英]Change the appearance of an InputRadio in a Blazor page
我是 Blazor 的新手,只是嘗試使用客戶端 WA 應用程序在 VS2022 中邁出第一步。
我不喜歡內置<InputRadio>
組件的外觀。 我想要實現的是一個按鈕式單選組。
我訪問了github 上的原始源(感謝微軟,感謝您使用 OS!) ,發現外觀似乎是在這里構建的:
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
Debug.Assert(Context != null);
builder.OpenElement(0, "input");
builder.AddMultipleAttributes(1, AdditionalAttributes);
builder.AddAttributeIfNotNullOrEmpty(2, "class", AttributeUtilities.CombineClassNames(AdditionalAttributes, Context.FieldClass));
builder.AddAttribute(3, "type", "radio");
builder.AddAttribute(4, "name", Context.GroupName);
builder.AddAttribute(5, "value", BindConverter.FormatValue(Value?.ToString()));
builder.AddAttribute(6, "checked", Context.CurrentValue?.Equals(Value));
builder.AddAttribute(7, "onchange", Context.ChangeEventCallback);
builder.CloseElement();
}
我的第一個想法是繼承此 class 並為BuildRenderTree()
使用自己的覆蓋。 但是Context
所需的InputRadioContext
是internal
的,現在這看起來像是一條死胡同。
我嘗試在<InputRadioGroup>
中使用按鈕,但無法正確處理這些事件。
問題:如何更改<InputRadio>
的外觀或自己創建類似廣播組的內容?
Brian Parker 的相關提示將我推向了這個解決方案,效果很好:
<EditForm Model=@someViewModel>
<InputRadioGroup @bind-Value=@someViewModel.TheInstance_via_Id>
@foreach (SomeClass e in someList)
{
<InputRadio class="btn-check" id=@e.Id Value=@e.Id />
<label class="btn btn-outline-primary" for=@e.Id>@e</label>
}
</InputRadioGroup>
</EditForm>
如果沒有</br>
標記,按鈕將顯示為籌碼雲。
提示:首先我嘗試在@bind-Value
中使用 object 本身,但發現魔法綁定不支持所有類型。 這就是為什么我向 ViewModel 添加了一個基於 Id 的綁定屬性,如下所示:
//the actual property returning an object's instance
public SomeClass TheInstance{ get; set; } = new SomeClass(Guid.NewGuid(), "n.A.");
//helps to magically bind <InputRadio> via Guid-Property
public Guid TheInstance_via_Id
{
//returns the actual object's id
get => TheInstance.Id;
//re-sets the actual object from a shared context store
set => TheInstance= BaseDataContext.ListOfInstances[value];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.