How to create a reusable 'GUI' in blazor?

Viewed 380

I am currently trying to create my first ever web application using Blazor. Before I have always programmed in WPF. I am trying to convert my wpf project to a asp.net core blazor project.

When working with wpf I am able to create a re-usable, user control that I can keep using depending on how many rows of data I have in my sql database. How do I do something similar to this in blazor? Is it possible to create a blazor page and then keep reusing it?

Any tips would be greatly appreciated.

2 Answers

Note: All the components in Blazor are reusable.

There are two types of components in Blazor: Routable components and non-routable components. Routable components are also called page components. They annotated with the Razor @page directive and route template, as for instance:

@page "/counter"

A routable component is one that you can navigate to with url... The default template creates a routable component named Counter, and you can navigate to it by clicking on the Counter menu item in the NavBar. The Counter component is in the role of a "page" here. But you may also embed it, as a child component, in the Index component, in which case the Counter component is reused, and as a child component

Thanks for your answer. I have managed to get a reusable razor page. Quick question. When I was doing this with wpf I used Tag to send data to the user control. How do I do this using blazor instead?

What you want is data-binding between a parent component and its child. The following is the code for the Counter component that is created in the default Blazor template:

Counter.razor

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

The following describes how to alter the component so that it gets a value from a parent component in which it is to be embedded.

Instead of having a local variable defined like this: private int currentCount = 0;, I want to pass the Counter component a numeric value from the parent component... In this case, I'll have to define a parameter property that will get the passed value:

[Parameter]
public int CurrentCount {get; set;};

So now you can use the passed value in your Counter component. This is how you embed the Counter component in the index component and pass it a value:

Index.razor

@page "/"
<div>@value</div>

<Counter CurrentCount="value" />

@code
{
   private int value = 100;
}

Think of Components as Blazor's version of user controls, and you should be quite comfortable adapting to Blazor.

Related