将按钮的内容设置为 <Image>通过样式 [英] Setting Button's Content to <Image> via Styles
本文介绍了将按钮的内容设置为 <Image>通过样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法让它工作:
<UserControl>
<UserControl.Resources>
<ResourceDictionary>
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
<Setter Property="Button.Content">
<Setter.Value>
<Image Source="D:Tempdictionary16.png"/>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<Button Style="{StaticResource TestStyle}"/>
<Button Style="{StaticResource TestStyle}"/>
</StackPanel>
</UserControl>
此代码抛出以下异常(指向第二个按钮):
This code throws the following exception (pointing to the second button):
指定的元素已经是另一个元素的逻辑子元素.先断开连接.
Specified element is already the logical child of another element. Disconnect it first.
推荐答案
该样式创建 Image
的一个实例,您不能像这样在两个地方使用它.您可以使用 x:Shared
= false
并在样式中引用它,然后将在每个使用该样式的地方创建一个新的.
The style creates one instance of the Image
, you cannot use it in two places like this. You can create the image as a separate resource with x:Shared
= false
and reference it in the style then a new one will be created in every place the style is used.
例如
<UserControl>
<UserControl.Resources>
<Image x:Key="img" x:Shared="false" Source="D:Tempdictionary16.png" />
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
<Setter Property="Content" Value="{StaticResource img}" />
</Style>
</UserControl.Resources>
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<Button Style="{StaticResource TestStyle}" />
<Button Style="{StaticResource TestStyle}" />
</StackPanel>
</UserControl>
这篇关于将按钮的内容设置为 <Image>通过样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文