xamlmaui-blazor

Maui BlazorHydrib Appp - x:Name attribute in .Razor pages not working


Sorry for the basic question but I can't seem to find the answer. When I create a sample project using VS 2022, it has three example pages: Counter.razor, Weather.razor, and Home.razor. Each page has more or less the following structure:

@Page
//HTML goes here
@Code
//Code for HMTL goes here

Now, say you have a button or a label and you want to change some of it's properties. Most examples I've found, they use the x:Name attribute and then reference in the code:

@Page
<Label x:Name="MyLabel" />
@Code
MyLabel.text = "Whatever you want it to be";

The problem is that that particular example is always in a .xmal page that works together with a xmal.cs file where you reference the code. Of course the .xmal page has the <PageContent> element where you can insert the proper links that give that functionality, but such thing is not available in the razor page (At least not that I can find it).

How can I make it work? I understand I could do something like this instead:

@Page

<Label> @StringForLabel </Label>

@Code

public String StringForLabel = "Change the text this way";

But this is incredibly annoying because I have to create variables for every single property as opposed to just mod properties on a label directly.

The other problem is that I seem to be missing some of the basic functionality. For example:

<Label Text="Some text"> </Label>  //Text="Some text" does nothing. 

I tried adding a xmal page component and do some basic test and it works, but how can it be done using .Razor pages?

I even tried doing adding the <PageContent> element with all of the appropriate links but it does not compile.

Thank you!

BMET1

enter image description here


Solution

  • The x:Name does not apply to the Blazor Razor component.

    For Razor components and DOM elements in Blazor apps, you can use Blazor data binding to achieve this.

    Razor components provide data binding features with the @bind Razor directive attribute with a field, property, or Razor expression value.

    The following example binds:

    An <input> element value to the C# inputValue field. A second <input> element value to the C# InputValue property. When an <input> element loses focus, its bound field or property is updated.

    Bind.razor

    @page "/bind"
    
    <PageTitle>Bind</PageTitle>
    
    <h1>Bind Example</h1>
    
    <p>
        <label>
            inputValue: 
            <input @bind="inputValue" />
        </label>
    </p>
    
    <p>
        <label>
            InputValue: 
            <input @bind="InputValue" />
        </label>
    </p>
    
    <ul>
        <li><code>inputValue</code>: @inputValue</li>
        <li><code>InputValue</code>: @InputValue</li>
    </ul>
    
    @code {
        private string? inputValue;
    
        private string? InputValue { get; set; }
    }
    

    For more information, please check document: Binding features.