Article directory
foreword
We often encounter component templating in WPF. Here is how Blazor solves it.
component template
Why component templates
Although after componentization, we can write code very quickly. But component templates allow us to write faster.
There is a need here. A student page and a teacher page are required.
Do not use component templates
student
<组件1/>
<组件2/>
<组件3/>
<组件4/>
....
<学生信息/>
teacher
<组件1/>
<组件2/>
<组件3/>
<组件4/>
....
<老师信息/>
After use
Declare components
<组件1/>
<组件2/>
<组件3/>
<组件4/>
....
<组件模板a/>
use components
<组件模板>
<组件模板a>
<学生信息/>
</组件模板a>
</组件模板>
<组件模板>
<组件模板a>
<老师信息/>
</组件模板a>
</组件模板>
code part
Tips: I used Yuanzu here as a temporary variable. This is the syntax of C#
<h3>Model</h3>
<table>
<thead>
@HeadTemplate
</thead>
<tbody>
@foreach(var item in Items)
{
<tr>@RowTemplate(item)</tr>
}
</tbody>
</table>
@code {
//内容模板
[Parameter]
public RenderFragment HeadTemplate {
get; set; }
//数据模板,使用元祖来作为数据源
[Parameter]
public RenderFragment<(string Name,string Age)> RowTemplate {
get; set; }
//数据源
[Parameter]
public IReadOnlyList<(string Name,string Age)> Items {
get; set; }
}
use
<Model Items="Lists">
<HeadTemplate>
<th>Name</th>
<th>Age</th>
</HeadTemplate>
<RowTemplate>
<!--@context是拿到数据模板的上下文,由于我们使用的是元祖,所以可以直接使用-->
<td>@context.Name</td>
<td>@context.Age</td>
</RowTemplate>
</Model>
@code{
public List<(string Name,string Age)> Lists{
get; set; }
protected override Task OnInitializedAsync()
{
Lists = new List<(string Name, string Age)>
{
("小王","11"),
("小刘","12"),
("小陈","13")
};
return base.OnInitializedAsync();
}
}
Is it different from directly binding data?
For higher control of components, how to bind data sources and display is limited by template components. Templates can be used to customize the display effect.