在WPF中,我能否在两个按钮之间共享相同的图像资源?

12
我想在WPF中创建一个开关按钮,并希望当用户单击它时,它可以改变外观(如果是打开状态则切换为关闭状态,如果是关闭状态则切换为打开状态),使用图像来实现。 我已将要使用的图像添加到资源中:
 <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>

事件代码中,“flag”是一个布尔局部变量,其初始值为true:

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

现在我需要创建两个行为相同的开关按钮。当我尝试为第二个按钮使用相同的资源时,发生了异常。
 Specified element is already the logical child of another element. Disconnect it first.

我可以在第二个按钮中使用相同的图像资源,还是必须再次添加具有不同键的图像资源作为资源?

3个回答

16

将你的样式中的“Shared”设为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}" />


12
你应该使用BitmapImage来进行图片分享。
<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"/>

接下来,您可以使用BitmapImage创建多个Image

XAML中:

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

在代码中
  Image image = new Image();
  image.Source = FindResource("Off1");
  OnOff1Btn.Content = image; 

1

虽然@Tilak的解决方案绝对是一种方法,但您也可以通过Style.Triggers来实现。

这里有一个例子(假设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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接