Customization
A guide to customizing the behavior of the primitives.
Change events
Parts raise change events such as OnOpenChange and OnValueChange before their state
changes, whether a pointer, a key, focus or your own code caused the change. Popups and panels have OnOpenChange, and parts with a value have OnValueChange:
[Parameter] public EventCallback<OpenChangeEventArgs> OnOpenChange { get; set; }
[Parameter] public EventCallback<ValueChangeEventArgs<T>> OnValueChange { get; set; }The event's arguments describe the change, and let you stop it:
OpenorValueis the state the part is about to change to.Reasonis what caused the change, so you can run side effects for some causes only. For popups it's anOpenChangeReason(TriggerPress,OutsidePress,EscapeKey...); for values it's a string such as"trigger-press","item-press"or"keyboard".Cancel()keeps the part's current state.Canceledsays whether a handler has canceled the change.
Canceling a change
Call Cancel() to stop a change from happening, for example to keep a tooltip open when its trigger is pressed (pressing the trigger would otherwise close it):
<TooltipRoot OnOpenChange="KeepOpenOnPress">
...
</TooltipRoot>
@code {
private void KeepOpenOnPress(OpenChangeEventArgs args)
{
if (args.Reason == OpenChangeReason.TriggerPress)
{
args.Cancel();
}
}
}The part keeps managing its own state, which is often simpler than controlling it with a field of your own and guarding every update.
Controlling a part with state
Parts manage their own state by default. A value you set once, such as Open="true" or
Value="@("apple")", is where it starts. To control a part from your own state, bind it, and it changes
whenever your field does:
<DialogRoot>
<DialogTrigger>Open</DialogTrigger>
</DialogRoot>The uncontrolled dialog opens when its trigger is pressed. Bound, a Dialog can open a second after the page loads, without a trigger:
<DialogRoot @bind-Open="_open">
No trigger is needed in this case.
</DialogRoot>
@code {
private bool _open;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1000);
_open = true;
}
}Binding also lets the rest of your component read the part's state.