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

时间秒杀一切 提交于 2019-12-23 07:40:58

问题


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?


回答1:


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}" />




回答2:


You should use BitmapImage for image sharing.

<BitmapImage x:Key="Off1" UriSource="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
<BitmapImage x:Key="On1" UriSource="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>

After that you can create Multiple Image with BitmapImage

In XAML

 <Button ..>
  <Button.Content>
   <Image Source="{StaticResource Off1}" />
  </Button.Content>
 </Button>

In Code

  Image image = new Image();
  image.Source = FindResource("Off1");
  OnOff1Btn.Content = image; 



回答3:


While @Tilak's solution is definitely one way to go, you can also do this via Style.Triggers

Here's an example (with the assumption that Flag is a public property exposing flag):

<Button Content="{StaticResource On1}">
    <Button.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Flag}" Value="false">
                    <Setter Property="Content" Value="{StaticResource Off1}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


来源:https://stackoverflow.com/questions/14110068/in-wpf-can-i-share-the-same-image-resource-between-2-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!