Using next block of code in windows.resource.
<Style TargetType="Button" x:Key="l1" >
<Setter Property="Button.Effect" >
<!--<Setter Property="BitmapEffect">-->
<Setter.Value>
<DropShadowEffect />
</Setter.Value>
</Setter>
<Setter Property="Content" >
<Setter.Value >
<StackPanel Orientation="Horizontal">
<Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
<TextBlock>Find</TextBlock>
</StackPanel>
</Setter.Value>
</Setter>
</Style>
It works only for one button, but as soon as I aply it to second button error generating during run-time.
<Button Height="23" HorizontalAlignment="Left" Margin="322,25,0,0" Name="Button18" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
<Button Height="23" HorizontalAlignment开发者_JAVA技巧="Left" Margin="586,37,0,0" Name="Button19" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
any solution for resolve this problem?
You cannot set the Content
of a ContentControl
directly this way. The reason for this is that the StackPanel
(to name just one) in your Content
setter is the same instance for all buttons that the style applies on; however, this is not allowed (and probably results in you getting the Element is already the child of another element exception).
Instead, you should set the ContentTemplate
property:
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
<TextBlock>Find</TextBlock>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
This will work because now a new visual tree branch will be created for each instantiation of the template (i.e. there will be as many StackPanel
s etc as you have buttons).
You can't set the content of a control through a style like that (at least not twice).
You should use a template to sent the content, like so:
<DataTemplate x:Key="buttonTemplate">
<StackPanel Orientation="Horizontal">
<Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
<TextBlock>Find</TextBlock>
</StackPanel>
</DataTemplate>
<Style TargetType="Button" x:Key="l1" >
<Setter Property="Button.Effect" >
<Setter.Value>
<DropShadowEffect />
</Setter.Value>
</Setter>
<Setter Property="ContentTemplate" Value="{StaticResource buttonTemplate}" />
</Style>
精彩评论