Reputation: 195
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.
Upvotes: 4
Views: 931
Reputation: 30072
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;
}
}
Upvotes: 2
Reputation: 14553
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 />
Upvotes: 4