Free Exam Guide 70-511: Resources Programmatically


There are three approaches that can access resources programmatically.  XAML is a mark-up language, not a programming language, if you are using C# or VB then you will need to utilize the resources are programmatically.

References:

 

Use FindResource and TryFindResource methods

  • These two methods use the keys that identify resources to retrieve resources
  • FindResource raises an exception if the resource is not found
  • Example line of code:
  • b.background =(Brush)this.FindResource(“whiteBrush”)
  • //Note: Will raise an error if whiteBrush isn’t found, I prefer this approach
  • TryFindResource method returns a null if the resource is not found
  • Example line of code:
  • b.background =(Brush)this.TryFindResource(“whiteBrush”)
  • //Note: Will return a null if whiteBrush isn’t found, plan on handling the null

Use the Resources property

  • Resources property can be referenced as a dictionary
  • Example code:
ResourceDictionary dict = new ResourceDictionary(); SolidColorBrush redBrush = new SolidColorBrush(Colors.Red); SolidColorBrush yellowBrush = new SolidColorBrush(Colors.Yellow); Double dblSlap = 200.0; dict.Add("yellowBrush", yellowBrush); dict.Add("redBrush", redBrush); dict.Add("dblSlap", dblSlap); this.Resources = dict;

Use SetResourceReference

This is not explained well and needs a separate blog entry to explain. 

In a two sentences:

  • Most resource usages will set the key of the resource to be a string. However, various WPF features deliberately do not use a string type to specify keys, instead this parameter is an object.
  • It isn’t that complicated, but it is complicated for me to explain right now.  So later on this one, it will make sense later.
Skip to main content