Wednesday, August 18, 2010

x:Shared for Sharing Resources

WPF has many cool features. One such feature is defining Resources. We can define content & data templates, styles and objects (including FrameworkElement instances) to be later used. Whenever WPF application demands the resource, runtime fulfills the request by gettting an instance from these resources. We can define these resources anywhere in the logical hierarchy, at application level or at cross-application level. It is good to know that a single instance is created for these resources and it is shared for different requests. Basically WPF runtime fulfills the request of resource by providing the same instance to the requester. There might be circumstances when we want new instance for each request e.g. we might define a FrameworkElement in Resource section and want a new instance every time it is requested. x:Shared is there for all those circumstances.

<Window x:Class="WPFComboBoxEditable.WindowXShared"
Title="WindowXShared" Height="356" Width="547">
<Rectangle x:Shared="false" x:Key="rect" Width="20" Height="20" Fill="Green" />
<Border Child="{StaticResource rect}" />
<Button Content="{StaticResource rect}" />
<Button Content="{StaticResource rect}" />

It must be remembered that we can only set x:Shared in XAML. It can not be set through code.

Visual Studio 2008 seems issues with usage of resources using x:Shared. That is why even if we disallow sharing [using x:Shared = false], it still can not load the designer.

It also shows it as error when we try to Load the Designer. Don't worry, it builds and run fine.

XAML also highlights this as error. If we hover over the highlighted text, it shows the error message. Remember this is just designer issue that it does not support that. As discussed above, the build should be fine.

The default value of x:Shared is true (x:Shared = true) that is why the resources are shared among all the components using them.

No comments: