Search code examples
wpfdynamicresource

What are the options to control the DynamicResource references?


Let's presume, that we want to create a UserControl and make it able to be styled by the caller.

What are the options we have in such a case?

  1. As I understand we can use DynamicResources in xaml of the UserControl.
  2. We can expose some DPs and bind the UserControl's elements to them.

Sometimes I face the situations when I use a UserControl but it can't be rendered on the screen. If this happens, I start to explore the solution and try to understand what resources can't be found by the UserControl.

This leads to the significant loss of time.

How can we prevent such the troubles?

A solution that I see is to write some code inside those UserControls which use DynamicResources with intention to try to find the required resources and throw an exception. It can simplify the debugging.

The more resources we have in a solution, the more headache we suffer from.


Solution

  • You should use the dependency properties and then the consumer/host of the control can bind dynamic resources to them either declaratively or programmatically.

    Don't go looking for dynamic resources yourself, this introduces a dependencies into your control, instead you should work with what you are given. You can default to in built styles if you're not given anything.

    The only time you should think about defaulting to externally defined dynamic resources is when you've got a really complex control (like a data grid) and you also supply theme assemblies (like control vendors do). Other than that, using the DP approach is more manageable and easier for you to document. In any case you shouldn't throw exceptions if dynamic resources are not found. If you are programmatically looking for a resource and fail to find it then have a default. If you are binding to a dynamic resources source declaratively in XAML then either let the normal binding error occur if it isn't found, or use a proxy dependency property combined with a data trigger