开发者

What exactly is "static" about a XAML static resource?

In what sense are XAML resources static?

By XAML resources I mean things declared in a resource block and accessed with the {StaticResource resource-name} syntax.

Do page resources behave as though they are static members on a page class? Or, were I to create multiple instances of a page class, would I get multiple instances of its resources?

Nomenclature implies that resources will be开发者_StackOverflow社区 handled like static members, which implies that multiple instances of a page would share a common set of resources.

Which behaviour will manifest?


Please note that the actual answer is in the comments on the accepted response. The important part is this link.


It has nothing in common with static types in c#.

Using StaticResource will evaluate the resource once, the first time that access is made i.e. Not at compile time.

A DynamicResource will be evaluated every time the resource is required.

Also note that the compiler doesn't evaluate resources at all, dynamic or static.


A copy of the resource dictionary is created with each WPF entity that defines it. The definition of static from a programming language simply does not apply here.

Here is an example:

Application
 |-ResourceDictionary
   |-Brush1
   |-Brush2
 |-CustomerWindow          x3
   |-ResourceDictionary   
     |-Brush3
     |-Brush4
   |-CustomerListControl   x2
     |-ResourceDictionary 
       |-Brush5
       |-Brush6

In this sample application we have two brushes defined in the application resourcedictionary, two brushes in CustomerWindow and another two in CustomerListControl. CustomerWindow has two instances of CustomerListControl and there are three windows open.

In total the following resources will be instantiated:

Brush1 - 1x (one Application)
Brush2 - 1x
Brush3 - 3x (three windows open)
Brush4 - 3x
Brush5 - 6x (three windows * two controls per window)
Brush6 - 6x

If you are concerned about resource usage, you should define the resource at the topmost level. So in this scenario, if all the brushes are defined on the application level, there would only be one instance of each no matter how many windows are open.

MSDN article about optimizing WPF performance is well worth a read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜