'Blazor Render Fragment Child Content to allow only certain components?
Is it possible to restrict the RenderFragment Child Content of a component to only allow certain components?
For example
<MyParentComponent>
<Children>
<AcceptedChild/>
<InvalidChild/> <-- throw err since it shouldn't be accepted
</Children>
</MyParentComponent>
EDIT:
<DataGrid>
<DataGridColumns>
<DataGridColumn/>
<DataGridColumn/>
<NotADataGridColumn/> <--- throw error
</DataGridColumns>
</DataGrid>
Solution 1:[1]
Is it possible to restrict the RenderFragment Child Content of a component to only allow certain components?
No.
A RenderFragment is a delegate. In your example the RenderFragment assigned to DataGridColumns belongs to the parent page/component, not DataGrid, and is run in the context of the parent by the Renderer. DataGrid only "knows" it as a delegate that conforms to the RenderFragment pattern. It has no access to the internal code, so has no way of knowing what it contains.
Solution 2:[2]
If your component contains two or more RenderFragment parameters, you can limit the valid selection of direct children when using your component.
E.g. if you have a component MyComponent with the following parameters:
[Parameter]
public RenderFragment FirstChild { get; set; }
[Parameter]
public RenderFragment SecondChild { get; set; }
and you try to use it as follows:
<MyComponent>
<FirstChild />
<SecondChild />
<ThirdChild />
</MyComponent>
<ThirdChild /> will throw error:
RZ9996 Unrecognized child content inside component 'MyComponent'. The component 'MyComponent' accepts child content through the following top-level items: 'MyFirstChildComponent', 'MySecondChildComponent'.
The equivalent in your example would be that Children e.g. contains parameters RenderFragment AcceptedChild and RenderFragment AcceptedChild2, but no RenderFragment InvalidChild.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrC aka Shaun Curtis |
| Solution 2 | Astrid E. |
