With this Blazor component:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @_a.CurrentCount</p>
<button class="btn btn-primary" onclick="@_b.IncrementCount">Click me</button>
@functions {
private readonly ClassA _a = new ClassA();
private readonly ClassB _b = new ClassB(_a);
class ClassA
{
public int CurrentCount { get; set; }
}
class ClassB
{
private readonly ClassA _classA;
public ClassB(ClassA classA)
{
_classA = classA;
}
public void IncrementCount() => _classA.CurrentCount++;
}
}
I get this error:
Error CS0236 A field initializer cannot reference the non-static field, method, or property '__Counter._a'
This thread explain how resolve this error in standard class:
Why can't you use 'this' in member initializers?
But for this, it needs a constructor.
Is it possible to add constructor in Blazor component?
How resolve this error?
Let's create a Blazor component to display details about the employees of an organization. To add a component to the project, right-click on the Pages folder and choose Add -> Razor Component. Refer to the following image. In the Add New Item- Blazor App dialog, provide the name EmployeeCard and click Add.
You can refresh the Blazor component using the SignalR concept without reloading the page. When using SignalR, saving the changes in one page notifies the changes made to other clients.
By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another. Get the passed Page1 parameter value in Page2.
To keep classes readonly you should to move to "code-behind". Then you can instantiate classes on constructor:
@page "/counter"
@inherits CounterBase
<h1>Counter</h1>
<p>Current count: @_a.CurrentCount ...
CounterBase.cs
using Microsoft.AspNetCore.Blazor.Components;
namespace YourApp.Pages
{
public class ClassA
{
public int CurrentCount { get; set; }
}
public class ClassB
{
private readonly ClassA _classA;
public ClassB(ClassA classA)
{
_classA = classA;
}
public void IncrementCount() => _classA.CurrentCount++;
}
public class CounterBase : BlazorComponent
{
protected readonly ClassA _a;
protected readonly ClassB _b;
//constructor
public CounterBase()
{
_a = new ClassA();
_b = new ClassB(_a);
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With