Sharing Resources in WPF/SL

I just stumbled across the problem where I wanted to share a specific Path element between different Buttons as their Content. I declared the Path in a ResourceDictionary

    <Path x:Key="MinusPath"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Data="{StaticResource MinusData}"
          Stretch="Fill"
          Stroke="Red"
          StrokeThickness="3" />

and referenced the Path in each Button with

<Button Content="{StaticResource MinusPath}"/>

This works for exactly one Button but not for more. You will get a XamlParseException with an InvalidOperationException as its InnerException. The problem is that you need a new Instance of the Path for each Button.

It actually took me quite a bit until I googled a solution for the problem and the solution is shockingly simply. You just need to add x:Shared=”false” to the Path declaration

    <Path x:Key="MinusPath"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Data="{StaticResource MinusData}"
          Stretch="Fill"
          Stroke="Red"
          StrokeThickness="3"
          x:Shared="false" />

Up to now I just didn’t know about this x:-Attribute because it is missing in Intellisense.

Category(s): Silverlight, WPF

Comments are closed.