The displayinfochanged event is triggered only randomly in .net maui

235 Views Asked by At
public MainPage()
{
    InitializeComponent();

    BindingContext = new CircleColorsViewModel();
    DeviceDisplay.Current.MainDisplayInfoChanged += Current_MainDisplayInfoChanged;
}
public void Current_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
    Shell.Current.DisplayAlert("title", $"Orient: {DeviceDisplay.Current.MainDisplayInfo.Orientation}", "ok");
}

I change the orientation but this handler above is triggered only randomly, on some occasions. It feels so straightforward but many times does nothing. What am I missing?

Thank you.

1

There are 1 best solutions below

6
ToolmakerSteve On

Might be a timing issue on emulator. Test on an actual device. Or try:

Dispatcher.Dispatch( async () =>
{
    await Task.Delay(100);
    Shell.Current.DisplayAlert(...
}
  • Dispatch delays the action until after Current_MainDisplayInfoChanged returns. Allowing any internal Maui logic to run. [Code was already on UI thread; but UI thread might be in an awkward state at this moment. Theory.]
  • Delay should ensure page is redrawn in new orientation before DisplayAlert.

Bottom line: I suspect that DisplayAlert attempts to run, but Maui's page renderer isn't yet in a good state after rotation. Maybe alert gets ignored because can't be completed (internal error that is quietly suppressed).