There are many MudButtons and MudMenus in a Blazor page and I am trying to remove repeated properties like Variant="Variant.Outlined" Color="Color.Primary" Size="Size.Medium".
So, I added custom MudButton razor component which inherits MudButton as the followings;
@inherits MudButton
@{
//Is it required?
base.BuildRenderTree(__builder);
}
@code {
protected override void OnInitialized()
{
base.OnInitialized();
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
}
protected override void OnParametersSet()
{
base.OnParametersSet();
}
}
@inherits MudMenu
@code {
protected override void OnInitialized()
{
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
this.EndIcon = Icons.Filled.KeyboardArrowDown;
this.IconColor = Color.Primary;
this.AnchorOrigin = Origin.BottomCenter;
}
}
However, the custom MudButton and MudMenu could not be rendered correctly - only text was displayed.
Is it any way to inherit MudComponent with original style kept?
Best regards.
Using a normal class file .cs
not .razor
. This stops the razor compiler being invoked and clobbering the inherited RenderFragment.
public class AppButton : MudButton
{
protected override void OnParametersSet()
{
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
base.OnParametersSet();
}
}
public class AppMenu : MudMenu
{
protected override void OnParametersSet()
{
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
this.EndIcon = Icons.Filled.KeyboardArrowDown;
this.IconColor = Color.Primary;
this.AnchorOrigin = Origin.BottomCenter;
base.OnParametersSet();
}
}
Now you have two new components inheriting mudblazor with defaults set. <AppButton />
and <AppMenu />
My referred way is to override them in CTor (as long as they are not required.). You can then set any specific preferences in the individual Razor declarations.
public class MyMudButton : MudButton
{
public MyMudButton()
{
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
}
}
If you want to use Razor you need to deal with the default RenderFragment.
@inherits MudButton
@this.ParentContent
@code {
public RenderFragment ParentContent;
public MyMudButton()
{
ParentContent = (builder) => base.BuildRenderTree(builder);
this.Variant = Variant.Outlined;
this.Color = Color.Primary;
this.Size = Size.Medium;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.