top of page
avicoren

Big Gotcha in navigation rail SelectionChanged event

Updated: Dec 23, 2021

The event that triggers when you change a tab is called 'SelectionChanged'.

It is attached to the TabControl UI control. Give a name to your TabControl in Xaml (for example Name="NavRail") and then use it in PS, like:

$NavRail.add_SelectionChanged({ Do something })

We will use this event to do stuff whenever we change pages (tabs). For example we can put a switch and then run a script block according to the page that was selected. That's very important for our app's functionality. HOWEVER, this event, although attached to the navigation rail, will be triggered on ALL 'SelectionChanged' events occur, including on its contained elements!

That's a big gotcha. Let's say you have a DataGrid on your page. Every time you select a row on that table, this TabControl event will be triggered. Oh boy.

So what's the cure for that? nothing that complicated. Every event has two variables available for us:

  1. $this - called the "sender". It contains a reference to the control/object that raised the event.

  2. $_ - called "Event Arguments". It contains the event data.

We just need to know the source object that triggered the event.

Take a look at the condition I've put:

$NavRail.add_SelectionChanged({
    if ($_.Source -like "System.Windows.Controls.TabControl*") {
        # Write a switch that will run a relevant block for each page
    }
})

So every time the event triggers it will ask who is the source, and only when the source is the TabControl itself - it will continue executing.

For the DataGrid itself I will write a separate 'SelectionChanged' event. It doesn't belong to the TabControl event.


Be careful guys! if you won't pay attention on that, your app will do some unexpected things.

189 views0 comments

Recent Posts

See All

コメント


bottom of page