【问题标题】:Change the appearance of an InputRadio in a Blazor page在 Blazor 页面中更改 InputRadio 的外观
【发布时间】:2022-01-12 17:04:19
【问题描述】:

我是 Blazor 的新手,正在尝试使用客户端 WA 应用在 VS2022 中迈出第一步。

我不喜欢内置<InputRadio> 组件的外观。我想要实现的是一个按钮样式的单选组。

问题:
如何更改<InputRadio> 的外观或自己创建类似广播组的内容?

我访问了original source on github (thank you, MicroSoft, for going 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();
}

我的第一个想法是从这个类继承并为BuildRenderTree() 使用自己的覆盖。但是Context 所需的InputRadioContextinternal,现在这看起来像是一条死胡同。

我尝试使用<InputRadioGroup> 中的按钮,但无法正确处理事件。

【问题讨论】:

  • 这个组件只是渲染一个<input type="radio" ...。可以应用普通 CSS 来修改它。它也适用于AdditionalAttributes,这意味着您放置在InputRadio 组件上的任何属性(类等)都将转移到input 元素。旁注:我使用source.dot.net
  • @BrianParker 谢谢,我会读到这个...我对 Web-UI 很陌生 :-)
  • @BrianParker 谢谢!经过一些反复试验,我想出了我在下面发布的解决方案。

标签: c# radio-button blazor blazor-webassembly appearance


【解决方案1】:

好吧,对于有经验的网络开发人员来说,这个解决方案相当简单,但我想发布一个答案来帮助像我这样的菜鸟:-)

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.Name</label>
     }
   </InputRadioGroup>
</EditForm>

如果没有&lt;br/&gt; 标签,按钮会显示为筹码云

提示:首先我尝试在@bind-Value 中使用对象本身,但发现魔法绑定 并不支持所有类型。这就是我向 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];
    } 

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多