Wednesday 17 October 2012

Refactoring WPF (IOException: Cannot Locate Resource)

CHECK STARTUPURI

Minimal Structure WPF

What is the minimal structure of a WPF Application, for example, when you go into Visual Studio and click to create a new WPF Application?

This is a guide to a bare-bones WPF application. In fact, you can happily write WPF applications without knowing the bare-bones, but at some point it's essential to look back and fully understand what's going on in order to move forward.

App.xaml, App.xaml.cs and StartupUri (VIRF = Very Important when Refactoring)

Look at App.xaml and App.xaml.cs. This represents a single logical unit, representing the Application (or more precisely a subclass of System.Windows.Application) implemented over two partial classes.

This is like Global.asax in ASP.NET land. It's where you can put shared resources to be shared across multiple windows. It also specifies (in the App.xaml "header element" the StartupUri which will be set to the auto-generated MainWindow.xaml). If you change the StartupUri to something that doesn't except (e.g. PainWindow.xaml instead of MainWindow.xaml you will get an IOException ("Cannot locate resource: PainWindow.xaml"). This can happen after a refactor where you can't decide the name for the MainWindow.xaml and then forget to change the StartupUri (or MSVS fails to change the StartUri automagically - it happens).

App.xaml.cs purports to be the "interaction logic" for App.xaml but in reality it is usually left empty. App.xaml is frequently underutilised in WPF projects and should be given more a higher profile by WPF developers.

MainWindow.xaml and MainWindow.xaml.cs

This contains the window XAML and the IntializeComponent code after which you can define your own initialization logic (e.g. creation of ViewModels etc).

Furthering your Understanding

To understand more completely what a WPF Application actually is, one can read the MSDN document describing System.Windows.Application and its parent classes.

No comments: