Blazor组件[Parameter]属性使用报错:找不到Values属性
解决Blazor组件参数“不存在”的报错问题
报错信息
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Object of type 'DashboardComponents.LineGraph' does not have a property matching the name 'Values'. System.InvalidOperationException: Object of type 'DashboardComponents.LineGraph' does not have a property matching the name 'Values'. at Microsoft.AspNetCore.Components.Reflection.ComponentProperties.ThrowForUnknownIncomingParameterName(Type targetType, String parameterName) at Microsoft.AspNetCore.Components.Reflection.ComponentProperties.SetProperties(ParameterView& parameters, Object target) at Microsoft.AspNetCore.Components.ParameterView.SetParameterProperties(Object target) at Microsoft.AspNetCore.Components.ComponentBase.SetParametersAsync(ParameterView parameters) at Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters)
问题根源
你的LineGraph组件中,所有标记为[Parameter]的属性都错误使用了static修饰符:
namespace DashboardComponents; public partial class LineGraph { [Parameter, EditorRequired] public static List<double> Values { get; set; } = new(); [Parameter, EditorRequired] public static double Scale { get; set; } [Parameter] public static double GraphWidth { get; set; } = 500; [Parameter] public static double GraphHeight { get; set; } = 300; [Parameter] public ComponentColors Colors { get; set; } = new(); }
Blazor的组件参数是实例属性,参数绑定机制只会识别组件实例的属性,而静态属性属于类本身,不属于任何组件实例,因此Blazor无法找到这些带static的参数,触发报错。
修复方案
移除所有[Parameter]属性的static修饰符,将它们改为实例属性:
namespace DashboardComponents; public partial class LineGraph { [Parameter, EditorRequired] public List<double> Values { get; set; } = new(); [Parameter, EditorRequired] public double Scale { get; set; } [Parameter] public double GraphWidth { get; set; } = 500; [Parameter] public double GraphHeight { get; set; } = 300; [Parameter] public ComponentColors Colors { get; set; } = new(); }
修改后,原调用代码(<LineGraph Values="@Values" Scale="5" />)即可正常识别并绑定参数。
补充说明
- Blazor组件基于实例运行,每个
<LineGraph>标签都会生成独立的组件实例,实例属性能保证每个组件拥有独立的参数值。 - 若需共享全局数据,可使用注入服务、级联参数或状态容器,而非用静态属性作为组件参数。
内容的提问来源于stack exchange,提问作者Nyan
相关产品推荐
相关产品推荐

