设置按钮的内容为&lt;图像和GT;通过样式 [英] Setting Button's Content to <Image> via Styles
本文介绍了设置按钮的内容为&lt;图像和GT;通过样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不能得到这个工作:
&LT;&用户控件GT;
&LT; UserControl.Resources&GT;
&LT;&ResourceDictionary中GT;
&LT;风格X:键=TestStyle的TargetType ={X:类型按钮}&GT;
&LT; setter属性=Button.Content&GT;
&LT; Setter.Value&GT;
&lt;图像源=D:\\ TEMP \\ dictionary16.png/&GT;
&LT; /Setter.Value>
&LT; /二传手&GT;
&LT; /样式和GT;
&LT; / ResourceDictionary的&GT;
&LT; /UserControl.Resources>
&LT; StackPanel的VerticalAlignment =顶部的HorizontalAlignment =左&GT;
&LT;按钮样式={StaticResource的TestStyle}/&GT;
&LT;按钮样式={StaticResource的TestStyle}/&GT;
&LT; / StackPanel的&GT;
&LT; /用户控件&GT;
这code抛出以下异常(指着第二个按钮):
指定的元素已经是另一个元素的逻辑子。首先断开连接。
块引用>解决方案的样式创建
图像的一个实例
,你不能在两个地方像这样使用它。共享$ C:你可以用X创建一个外部资源字典中的形象$ C>
= FALSE
,并在风格,那么一个新的将在每次使用的样式地方创建引用它。例如
&LT;&用户控件GT;
&LT; UserControl.Resources&GT;
&lt;图像X:键=IMGX:共享=假来源=D:\\ TEMP \\ dictionary16.png/&GT;
&LT;风格X:键=TestStyle的TargetType ={X:类型按钮}&GT;
&LT; setter属性=内容VALUE ={StaticResource的IMG}/&GT;
&LT; /样式和GT;
&LT; /UserControl.Resources>
&LT; StackPanel的VerticalAlignment =顶部的HorizontalAlignment =左&GT;
&LT;按钮样式={StaticResource的TestStyle}/&GT;
&LT;按钮样式={StaticResource的TestStyle}/&GT;
&LT; / StackPanel的&GT;
&LT; /用户控件&GT;Can't get this to work:
<UserControl> <UserControl.Resources> <ResourceDictionary> <Style x:Key="TestStyle" TargetType="{x:Type Button}"> <Setter Property="Button.Content"> <Setter.Value> <Image Source="D:\Temp\dictionary16.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.
解决方案The style creates one instance of the
Image
, you cannot use it in two places like this. You can create the image in an external resource dictionary withx:Shared
= false
and reference it in the style then a new one will be created in every place the style is used.
e.g.
<UserControl> <UserControl.Resources> <Image x:Key="img" x:Shared="false" Source="D:\Temp\dictionary16.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>
这篇关于设置按钮的内容为&lt;图像和GT;通过样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文