我想在 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;
}
}
现在我需要创建 2 个开/关按钮,其行为相同。
当我尝试对第二个按钮使用相同的资源时,出现异常:
Specified element is already the logical child of another element. Disconnect it first.
我可以在第二个按钮中使用相同的图像资源,还是必须再次将图像添加为具有不同密钥的资源?
将样式中的 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}" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)