Question

I am having a lot of "fun" trying to make my margins (and widths) in my XAML fit together with other margins in the same application and margins in other applications in the same "suite" of applications.

So I got the idea to define margins as staticresources:

<Thickness x:Key="MarginDetailTabPageContent">0</Thickness>
<Thickness x:Key="MarginLeftHeader">2,4,2,2</Thickness>
<Thickness x:Key="MarginAdditionalInfoOnTop">1,2,2,0</Thickness>
<Thickness x:Key="MarginSmallHeaderOnTop">1,2,2,0</Thickness>
<Thickness x:Key="MarginFieldWithAdditionalMarginOnTop">0,0,2,2</Thickness>
<System:Double x:Key="WidthSmallField">70</System:Double>

..and then I plan to use these staticresources everywhere.. labels, textblocks, textboxes, checkboxed .. on almost all controls in my application.

But before I make this rather time-consuming change, I would like your expert opinion on how this would affect performance.

Somehow, in my mind, I've decided that using the staticresource - writing <TextBlock Margin="{StaticResource=MarginLeftHeader}" ... /> instead of <TextBlock Margin="2,4,2,2" ... /> - everywhere costs at least a call to some function for each place it is used. It this right?

The overall question is: would the user be able to feel any change in performance (for the worse.. or for the better)?

Was it helpful?

Solution

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. So there is no significant difference in performance; lookup behavior for that resource is analogous to compile-time lookup.

OTHER TIPS

Having several instances of <TextBlock Margin="2,4,2,2" ... /> in your app will cause a new and separate Thickness object to be created for each one.

Having a single Thickness resource, and several instances of <TextBlock Margin="{StaticResource MarginLeftHeader}" ... /> will create only one Thickness object, with several references to it.

A few factors:

  • The second option would use less memory than the first (i.e. less Thickness objects in memory).
  • The second option would make life much easier if it came to tweaking the margins of your application globally, or providing different margins in different situations.
  • I'm not sure which option would perform better - instantiating new Thickness objects versus looking up resources. My gut feeling is that for a simple Thickness struct, the first option might actually perform better (whereas it could be different for more complicated class-based objects)

In summary, because you're dealing with a simple Thickness struct of only four double values, the memory and performance differences will probably be fairly negligible, so do whichever you prefer!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top