Finding Resources in a WPF Application

FindResource method finds user interface resources such as a Font or Brush. This method takes key of the resource and if resource is not found, it throws an exception. If a resource is found, this method returns it as an object. You must cast this object to the respective resource before you use it.

FindResource method first looks resources on the application level that are available from the Resources property of the Application class. If resource is not found in the application resources, it looks in the System resources including SystelColors, SystemFonts, and SystemParameters.

The code listed in Listing 1 uses FindResource method to find YellowSolidBrush and converts the object to a SolidColorBrush.

try

{

    object res = Application.Current.FindResource("YellowSolidBrush");

    SolidColorBrush yellowBrush = (SolidColorBrush)res;

}

catch (ResourceReferenceKeyNotFoundException resExp)

{

    MessageBox.Show("Resource not found., " + resExp.Message);
}
    

Listing 1

If a resource is not found, the FindResource method throws an exception. TryFindResource method does same what FindResource does accept when a resource is not found, TryFindResource does not throw an exception.

The code listed in Listing 2 uses TryFindResource method to find YellowSolidBrush and if returned object is not null then it converts the object to a SolidColorBrush.

object res = Application.Current.TryFindResource("YellowSolidBrush");

if (res != null)

{

    SolidColorBrush yellowBrush = (SolidColorBrush)res;
}

Listing 2