Search code examples
c#.netasp.net-coreblazormudblazor

Stop OnKeyDown event propagation


I have a MudTextField component which is bound to a decimal value and I want to erase the default 0 value when the user starts typing numbers. I've used the OnKeyDown event but I see it gets propagated even after I handle it and the number typed by the user gets inserted twice. args.StopPropagation does not seem to exist in Blazor or MudBlazor.

<MudTextField @bind-Value="_tripModel!.TripLength" Label="Length" Variant="Variant.Text" OnKeyDown="k => OnMileageKeyDown(k)"></MudTextField>


    
private void OnMileageKeyDown(object args)
{
    if (_tripModel!.TripLength == 0 && args is KeyboardEventArgs)
    {
        string keyChar = ((KeyboardEventArgs)args).Key;
        bool success = int.TryParse(keyChar, out int keyInt);
        if (success)
        {
            _tripModel!.TripLength = keyInt;
            // ((KeyboardEventArgs)args).StopPropagation = true; // Not working
            StateHasChanged();
        }
    }
}

How can I stop event propagation?


Solution

  • It would be easier if you use focus/focusout event instead.

    <MudTextField @bind-Value="TripLength" Label="Length" Variant="Variant.Text" @onfocus="e => Clear0(e)" @onfocusout="e => Restore0(e)"></MudTextField>
    @code{
    
        private decimal? TripLength = 0;
        private void Clear0(FocusEventArgs e)
        {
            if (TripLength == 0)
            {
                TripLength = null; 
            }
        }
        private void Restore0(FocusEventArgs e)
        {
            if (TripLength == null) 
            {
                TripLength = 0;
            }
        }
    }