C# Blazor Error BL0005 - Setting Component Properties Properly

Viewed 732

I have done the research I can on this error and just not understanding the correct solution.

Example code (taken directly from the vendors sample)
https://blazor.syncfusion.com/documentation/menu-bar/getting-started/

<SfMenu Items="@MenuItems"></SfMenu>

@code {
    public List<MenuItem> MenuItems = new List<MenuItem>{
        new MenuItem{ Text = "File", Items = new List<MenuItem>{
            new MenuItem{ Text= "Open" },
            new MenuItem{ Text= "Save" },
            new MenuItem{ Text= "Exit" }}
    },
        new MenuItem{ Text = "Edit", Items = new List<MenuItem>{
            new MenuItem{ Text= "Cut" },
            new MenuItem{ Text= "Copy" },
            new MenuItem{ Text= "Paste" }}
    },
        new MenuItem{ Text = "View", Items = new List<MenuItem>{
            new MenuItem{ Text = "Toolbars" },
            new MenuItem{ Text = "Zoom" },
            new MenuItem{ Text = "Full Screen" }}
    },
        new MenuItem{ Text = "Tools", Items = new List<MenuItem>{
            new MenuItem{ Text= "Spelling & Grammar" },
            new MenuItem{ Text= "Customize" },
            new MenuItem{ Text= "Options" }}
    },
        new MenuItem{ Text = "Go" },
        new MenuItem{ Text = "Help" }
    };
}

This will generate the BL0005 Component parameter 'Text' should not be set outside it's component. It will do that with all of the parameters.

This is code setting the variable to pass to the child component. I see no other way of setting this. There is no individual setter provided by the component. I really don't understand how the VS team wants me to build and pass this data (and obviously the vendor doesn't either if their code compiles with the same warnings).

Can anyone provide a concrete example of how this should be done?
I have read Correct way to mutate a component property in blazor but I obviously can't modify the child component in this case since it is a third party library.

1 Answers

Properties decorated with [Parameter] aren't supposed to be set via code because the OnParametersSet lifecycle methods won't get called, so they are only supposed to be set by the parent component in razor markup.

In your case, because the values won't change it should be okay to ignore those warnings. If you create the menu items in a code behind file (MyComponent.razor.cs) you can do this

public partial class MyComponent
{
  protected override void OnInitialized() 
  {
#pragma warning disable BL0005
    // create the menu structure here
#pragma warning restore BL0005
  } 
} 
Related