在 WPF 中,我可以在 2 个按钮之间共享相同的图像资源吗 [英] In WPF, can I share the same image resource between 2 buttons
问题描述
我想在 WPF 中创建一个开/关按钮,并且我希望它在用户单击它时更改其外观(如果它是打开切换到关闭,如果它关闭切换到打开)使用图像.我在资源中添加了我想使用的图片:
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>
事件代码是,flag"是一个布尔局部变量,初始化为真:
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;
}
}
现在我需要创建 2 个开/关按钮,它们的行为相同.当我尝试为第二个按钮使用相同的资源时,出现异常:
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.
我可以在第二个按钮中使用相同的图像资源,还是必须再次将图像添加为具有不同 Key 的资源?
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?
推荐答案
在你的风格中设置 Shared 为 false
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}" />
这篇关于在 WPF 中,我可以在 2 个按钮之间共享相同的图像资源吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!