2

Is there a way to tell in a blazor child component when a cascading parameter has been changed? I have a combo box in main layout and I am trying to cascaded the selected value down to child components. But not sure how to tell from the child component when the value has changed. Is this possible?

// MainLayout.razor file

//    <CascadingValue Value="@selectedAddress.Id">
//          @Body
//    </CascadingValue>

The index.razor file is what is accessing the cascading parameter.
0

1 Answer 1

6

Yeah, it's no problem. You can catch changes to the variable in its get; set;

CascadeChild.razor

@Message
    
@code {
    int _ID;
    [CascadingParameter]
    public int ID {
        get { return _ID; }
        set {   int lastValue = _ID;        // HERE //
                _ID = value; 
                if (lastValue != value) DoChange(); }
    }
    string Message = "";
    void DoChange()
    {
        Message = "Value has been changed to " + _ID;
    }
}

parent.razor

<CascadingValue Value="CurrentValue">
    <CascadeChild />
</CascadingValue>

<button @onclick="ChangeCurrentValue">Change</button>

@code {
    int CurrentValue;
    Random rand = new Random();

    void ChangeCurrentValue()
    {
        CurrentValue = rand.Next();
    }
}

https://blazorfiddle.com/s/nfjql5sg

1
  • It does not work for me. The _ID and ID has the same value as soon as it hits the first line of the set.
    – Calango
    Commented Sep 14, 2023 at 16:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.