Tuesday, January 10, 2023

Adding Pivot Item causes massive crash in UWP XAML

 Surprise exception when adding PivotItem

Quick background: my Simple Wi-Fi Analyzer program is getting a hidden feature which is unlocked by manipulating the UX in a secret way. I won't say what the secret is, but you can always look for "Unlock" in the source code :-)

The Analyzer app uses the nice Pivot control: I define a bunch of tabs for different features, and the user picks the tool they want to use. The new feature is a hidden tab, and my unlock code simply unhides it.

Except it doesn't. You can't actually hide a PivotItem in a Pivot control; it's not supported. Instead you have to create the PivotItem in code and then add it to the pivot.Items collection, it is shows right up!

Except you actually get this Vista-era dialog:

The problem (not even on Stack Overflow) is simple: you can't update a pivot.Items collection while you're in a PivotSelectionChanged callback! The solution is to 

Instead add in code like this:

                    var task2 = this.Dispatcher.RunIdleAsync((arg) => {

You don't have to wait for the task; it will just run when it's appropriate.

No comments: