Home > Back-end >  Blazor click calculator
Blazor click calculator

Time:11-24

I´m a C# beginner and I want to code a calculator with C# and blazor but I dont know how. My HTML is already finished, but I dont know how the blazor interface works Here is my HTML: Can anyone say to me how I have to start with that?

  @page "/calculator"
<PageTitle>Calculator</PageTitle>

<h1>Calculator</h1>
<div class="display">  
<p id="output">0</p>
<div class="first-row">
   <button id="r1-1">C</button>
   <button id="r1-3">%</button>
   <button id="r1-4">/</button>
</div>
<div class="second-row">
   <button id="r2-1" >7</button>
   <button id="r2-2" >8</button>
   <button id="r2-3" >9</button>
   <button id="r2-4" >x</button>
</div>
<div class="third-row">
   <button id="r3-1" >4</button>
   <button id="r3-2" >5</button>
   <button id="r3-3" >6</button>
   <button id="r3-4" >-</button>
</div>
<div class="fourth-row">
   <button id="r4-1"  >1</button>
   <button id="r4-2"  >2</button>
   <button id="r4-3"  >3</button>
   <button id="r4-4"  > </button>
</div>
<div class="fifth-row">
  <button id="r5-1" >0</button>
  <button id="r5-2" >.</button>
  <button id="r5-3" >=</button>
</div>
 </div>

@code {
    
}

CodePudding user response:

you can attach click event like this.

 <button id="r4-1" OnClick="@OnOneClicked(1)" >1</button>

@code {
    public void OnOneClicked(int number)
    {
        //do your thing for pressing 1;
    }
}

CodePudding user response:

For blazor buttons you'd add the onclick function.

for example:

<button @onclick="SomeFunction(5)" id="r5-3">5</button>

@code
{
   public Task SomeFunction(int number)
   {
     Console.WriteLine(number);
   }
}

CodePudding user response:

You will need an onclick event but there is no easy way to find out who was clicked, so pass in the value for digits. The operator buttons will need dedicated methods.

 <p id="output">@currentValue</p>

<button id="r2-1" @onclick="() => Digit(7)">7</button>
-- use Digit(x) for 9 other butons

<button id="r5-3" @onclick="Equals">=</button>
@code {

    string currentValue = "0";

    void Digit(int digit)
    {
        currentValue  = digit;
    }

    void Equals()
    {
        // ...
    }
}
  • Related