first_page

More Tired-ass WPF Notes…

I have just learned to appreciate DynamicResource after assuming I would never have to use it. This WPF declaration becomes necessary (for my work) when a centralizing Resource Dictionary, containing my ViewModel data sources, needs to be seen at design time (in Expression Blend) and run time. It follows that data contexts can be set like this:DataContext={DynamicResource MyViewModelKey} My previous technique was like this:DataContext={Binding Source={StaticResource MyViewModelKey}} Buy this book at Amazon.com! Comparing the two forms, gives me the chance to note that Binding.Source does not work with DynamicResource. The error messages thrown at me for this fact helped me to conclude incorrectly that DataContext cannot be set to DynamicResource. After a few experiments in Expression Blend it became clear to me that this is not the case.

Now the other stuff picked along the way, loosely related:

  • I’ve decided to use Laurent Bugnion’s IsInDesignMode property in ViewModelBase. This allows me to make ViewModel types with parameter-free constructors—and the use of the conventional d:DataContext, etc. for design-time stuff in Blend is needed less.
  • The attribute d:IsDataSource turns out to be very important in Blend. Without this attribute you can’t find ViewModel classes under the Data tab in Blend. I’m too tired right now to explain this more clearly.
  • StaticResource, DynamicResource, x:Static—what’s all this about?” by Tamir Khason tries to explain other stuff.
  • Here’s an MSDN reason why I held out against DynamicResource for so long: “A StaticResource must not attempt to make a forward reference to a resource that is defined lexically further within the XAML file. Attempting to do so is not supported, and even if such a reference does not fail, attempting the forward reference will incur a load time performance penalty when the internal hash tables representing a ResourceDictionary are searched. For best results, adjust the composition of your resource dictionaries such that forward references can be avoided. If you cannot avoid a forward reference, use DynamicResource Markup Extension instead.”
  • StackOverflow.com: “What’s the difference between StaticResource and DynamicResource in WPF?”—“A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored. A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.”

rasx()