堆栈面板风格
使用 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>
它仅适用于一个按钮,但一旦我将其应用于第二个按钮,就会在运行时生成错误。
<Button Height="23" HorizontalAlignment="Left" Margin="322,25,0,0" Name="Button18" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
<Button Height="23" HorizontalAlignment="Left" Margin="586,37,0,0" Name="Button19" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
有什么解决方案可以解决这个问题吗?
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="Left" Margin="586,37,0,0" Name="Button19" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
any solution for resolve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能以这种方式直接设置
ContentControl
的Content
。其原因是Content
setter 中的StackPanel
(仅举一个例子)对于应用该样式的所有按钮来说都是同一个实例;但是,这是不允许的(并且可能会导致您收到 Element is has the child of another element 异常)。相反,您应该设置
ContentTemplate
属性:这将起作用,因为现在将为模板的每个实例创建一个新的可视化树分支(即,将有尽可能多的
StackPanel
等,因为你有按钮)。You cannot set the
Content
of aContentControl
directly this way. The reason for this is that theStackPanel
(to name just one) in yourContent
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: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: