In WPF, can I share the same image resource between 2 buttons

Tamar Cohen picture Tamar Cohen · Jan 1, 2013 · Viewed 8.7k times · Source

I want to create a On/Off button in WPF and I want it to change its appearance when the user clicks it (if it was on switch to off, if it wad off switch to on) using images. I added the images I want to use to the resources:

 <Window.Resources>
    <Image x:Key="Off1" Source="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
    <Image x:Key="On1" Source="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>
 </Window.Resources>

And the event code is, "flag" is a Boolean local variable initialize as true:

 private void OnOff1Btn_Click(object sender, RoutedEventArgs e)
    {
        if (flag)
        {
            OnOff1Btn.Content = FindResource("Off1");
            flag = false;     
        }
        else
        {
            OnOff1Btn.Content = FindResource("On1");
            flag  = true;
        }
    }

Now I need to create 2 on/off buttons, that behave the same. When I tried to use the same resources for the second button I got an exception:

 Specified element is already the logical child of another element. Disconnect it first.

Can I use the same images resources in the second button or do I have to add the images again as resources with different Key?

Answer

Artiom picture Artiom · Oct 11, 2013

Set Shared in your style to false

<StackPanel >
   <StackPanel.Resources>
      <Image x:Key="flag" Source="flag-italy-icon.png" Width="10" x:Shared="false"/>
   </StackPanel.Resources>

   <ContentControl Content="{DynamicResource flag}" />
   <ContentControl Content="{DynamicResource flag}" />