WPF: Exception handling suggestions
XAML and Exception Handling is quite a tricky combination. And while I understand that it hard to design a robust and serving way of catching errors in XAML world it always feels a bit like way back when we had no exceptions; just breaking applications.
In general my WPF apps break down on the Application.Run() with, when I’m lucky, some vague exception deep down the list of inner exceptions.
It logical: there’s no user code running, in fact, all we program in XAML is object state and the moment it gets loaded into memory it is the WPF runtime that’s running the code. Nothing to debug, catch or handle there that is specific to my code.
In this post[1] Karsten explains how to handle exception in a WPF application. It feels like programming the global.asax in ASP.NET to do exceptionhandling.
My suggestion to Microsoft is (are you listening?): Provide an extra event for each(?) WPF element so I can code like this:
1: <Window x:Class=”_1_Hello.Window1″
2: >=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
3: >=”http://schemas.microsoft.com/winfx/2006/xaml”
4: Title=”_1_Hello” HandleException=”Window1_HandleException”
5: >
6: <Grid VerticalAlignment=”Center” HorizontalAlignment=”Center”>
7: <Grid ShowGridLines=”True” HandleException=”InnerGrid_HandleException”>
8: <Grid.RowDefinitions>
9: <RowDefinition>
10: </RowDefinition>
11: <RowDefinition>
12: </RowDefinition>
13: </Grid.RowDefinitions>
14: <Grid.ColumnDefinitions>
15: <ColumnDefinition></ColumnDefinition>
16: <ColumnDefinition></ColumnDefinition>
17: </Grid.ColumnDefinitions>
18: <Label Grid.Column=”0″ Grid.Row=”0″>Hello World</Label>
19: <Button Grid.Column=”1″ Grid.Row=”1″ Click=”OkButtonClick”>Ok</Button>
20: </Grid>
21: </Grid>
22: </Window>
This way exceptions can be bubbled up or handled on a lower level in context.