Search code examples
c#blazormudblazor

MudDatePicker DefaultValue plus DateChange


I want to use MudDatePicker element in a way where I need to be able to set a default value on load but at the same time define a onChange event for it. I am trying to do this but error says:

The component parameter is used two or more times for this component

Is there a way I can do this?

<MudDatePicker @bind-Date="@DefaultValue.Value" Label="Date" DateChanged="OnDateChange"
        Required="true" Class="mb-3" />

Solution

  • If you have a two-way binding in Blazor i.e. @bind-Date="date", you can convert it to a one-way binding with a change event which must set the value. The two-way binding is just syntax sugar and will do the same behind the scene.

    <MudDatePicker Date="@_date" Label="Date" DateChanged="OnDateChange"
            Required="true" Class="mb-3" />
    
    @inject ISnackbar Snackbar
    
    @code {
        DateTime? _date = new DateTime(2021, 12, 24);
    
        void OnDateChange(DateTime? newDate)
        {
            _date=newDate;
            // here you can do something when the date changes.
            Snackbar.Add($"Date changed to {_date}");
        }
        
        
    }
    

    Here is a snippet which you can play around with: https://try.mudblazor.com/snippet/mYcPFPvLnlyEHeOF