Blazor Server通用按钮组件报错:Action转EventCallback失败求解
解决Blazor自定义组件EventCallback类型转换错误
错误根源
父组件中误用DOM原生onclick事件绑定组件参数,导致System.Action与EventCallback类型不匹配,引发强制转换异常。
解决步骤
修正子组件的EventCallback参数命名与绑定
将子组件的事件参数改为Blazor规范的PascalCase命名,并简化事件绑定逻辑:@* StyledButtton.razor 修改后代码 *@ <div @onclick="OnClick" class="styled-btn" style="width: @Width; height: @Height; border-radius: @BorderRadius;"> <i class="@IconClass" style="font-size: @IconSize; color: @IconColor"></i> </div> <style> .styled-btn { display: flex; align-items: center; background-color: #fff; justify-content: center; margin: 0 5px; box-shadow: 0px 0px 2px 1px rgb(0 0 0 / 30%); } .styled-btn:hover { box-shadow: 0px 0px 6px 3px rgb(0 0 0 / 20%); transition: all 0.3s ease; } .styled-btn:active { background-color: #ffd800; transition: all 0.1s ease; } </style> @code { [Parameter] public string Width { get; set; } [Parameter] public string Height { get; set; } [Parameter] public string BorderRadius { get; set; } [Parameter] public string IconColor { get; set; } [Parameter] public string IconClass { get; set; } [Parameter] public string IconSize { get; set; } [Parameter] public EventCallback OnClick { get; set; } // 改为PascalCase命名 }修正父组件的参数绑定方式
使用kebab-case格式绑定组件的OnClick参数(Blazor自动映射PascalCase参数):@* Equipment.razor 修改后代码 *@ <TitleBar> <StyledButton BorderRadius="10px" Width="40px" Height="40px" IconColor="Black" IconSize="20px" IconClass="fa-solid fa-power-off" on-click="@ToggleSelectionMode"></StyledButton> </TitleBar> @code { public Syncfusion.Blazor.Grids.SelectionType SelectionType { get; set; } = Syncfusion.Blazor.Grids.SelectionType.Single; void ToggleSelectionMode() { if (SelectionType == Syncfusion.Blazor.Grids.SelectionType.Single) { SelectionType = Syncfusion.Blazor.Grids.SelectionType.Multiple; } else { SelectionType = Syncfusion.Blazor.Grids.SelectionType.Single; } } }
关键说明
- Blazor组件参数需遵循PascalCase命名规则,父组件中对应使用**kebab-case(短横线分隔)**属性名进行绑定,避免与DOM原生事件混淆。
- 直接将
EventCallback绑定到DOM事件(如@onclick="OnClick")是Blazor推荐的写法,无需额外包装lambda表达式。
内容的提问来源于stack exchange,提问作者Alex Wright
相关产品推荐
相关产品推荐

