0

All documentation regarding using two way binding claims that in order to have two way binding in a custom component you need to use an EventCallback. And yet when using a List it works automatically. I would like to know why?

Example Page index.razor:

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt ListOfValues="@ListOfValues" StringValue="@StringValue" />

<div @onclick="WriteValues">then click me</div>


@code {
    List<string> ListOfValues { get; set; } = new();
    public string StringValue { get; set; } = "";
    private void WriteValues()
    {
        foreach(var v in ListOfValues){
            Console.WriteLine($"ListOfValues: {v}");
        }
        Console.WriteLine($"StringValue: {StringValue}");
    }
}

Example component SurveyPrompt.razor:

<div class="alert alert-secondary mt-4">
   
    <div @onclick="bubu">click me</div>
   
</div>

@code {
    [Parameter] public List<string> ListOfValues { get; set; } = new();
    [Parameter] public string StringValue { get; set; } = "";

    private void bubu()
    {
        ListOfValues.Add("First Value set in a component");
        ListOfValues.Add("Second Value set in a component");
        
        StringValue = "A Value set in a component";
    }
}

When running the app and clicking on "click me" and then clicking on "then click me" The console will show that the ListOfValues variable has values in index.razor that were filled in SurveyPrompt.razor but StringValue remains empty

How page looks:

enter image description here

How console looks after clicking on "click me" and then on "then click me":

enter image description here

1 Answer 1

4

In the case of List<T>, it is not an effect of binding that you observe. What happens is that in your index.razor page you create a list (ListOfValues) which you then pass to your SurveyPrompt. Note that you do not copy the list, you pass it by reference. Both index.razor and SurveyPrompt "share" the same list instance. Therefore, when you make changes to the list, they are visible by everything that keeps a reference to it.

Strings, though, are immutable. When you change the string, you do not modify the original string, but create a new one in memory that replaces the old one. As a result, after the modificaton, index.razor and SurveyPrompt have two separate strings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.