C# 在WPF中,我可以在两个按钮之间共享相同的图像资源吗
我想在WPF中创建一个开/关按钮,我想让它在用户使用图像单击它时改变它的外观(如果是开-关,如果是关-开)。 我将要使用的图像添加到资源中:C# 在WPF中,我可以在两个按钮之间共享相同的图像资源吗,c#,wpf,xaml,resourcedictionary,bitmapsource,C#,Wpf,Xaml,Resourcedictionary,Bitmapsource,我想在WPF中创建一个开/关按钮,我想让它在用户使用图像单击它时改变它的外观(如果是开-关,如果是关-开)。 我将要使用的图像添加到资源中: <Window.Resources> <Image x:Key="Off1" Source="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" /> <Image x:Key="On1" Source="/WPFAp
<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>
现在我需要创建两个开/关按钮,它们的行为相同。
当我尝试为第二个按钮使用相同的资源时,出现了一个异常:
Specified element is already the logical child of another element. Disconnect it first.
我可以在第二个按钮中使用相同的图像资源,还是必须使用不同的键再次添加图像作为资源 您应该使用它来共享图像
<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"/>
虽然@Tilak的解决方案肯定是一种方法,但您也可以通过
Style.Triggers来实现这一点
下面是一个示例(假设标志
是公共属性公开标志):
将样式中的共享设置为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}" />
<Button ..>
<Button.Content>
<Image Source="{StaticResource Off1}" />
</Button.Content>
</Button>
Image image = new Image();
image.Source = FindResource("Off1");
OnOff1Btn.Content = image;
<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>
<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}" />