Silverlight:为什么这种风格不起作用?
我正在使用 Silverlight 4。我有一个按钮:
<Button Click="addTopicButton_Click">
<Image Source="/PlumPudding;component/Images/appbar.add.rest.png" />
</Button>
看起来不错。但是,当我尝试使用 Style
设置其 Content
时,没有显示任何内容:
<Style x:Name="AddButton" TargetType="Button">
<Setter Property="Content">
<Setter.Value>
<Image Source="/PlumPudding;component/Images/appbar.add.rest.png" />
</Setter.Value>
</Setter>
</Style>
<Button Click="addTopicButton_Click" Style="{StaticResource AddButton}" />
按钮为空。这是为什么呢?
I'm using Silverlight 4. I have a button:
<Button Click="addTopicButton_Click">
<Image Source="/PlumPudding;component/Images/appbar.add.rest.png" />
</Button>
It looks fine. However, when I try to set its Content
using a Style
, no content appears:
<Style x:Name="AddButton" TargetType="Button">
<Setter Property="Content">
<Setter.Value>
<Image Source="/PlumPudding;component/Images/appbar.add.rest.png" />
</Setter.Value>
</Setter>
</Style>
<Button Click="addTopicButton_Click" Style="{StaticResource AddButton}" />
The button is empty. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在样式中包含 UIElement(例如
Image
)并不是一个好主意。这样的对象仅在 Xaml 解析期间将样式放在一起时创建一次。关于 UIElements 需要理解的一件重要事情是,单个实例只能在可视化树中出现一次。因此,即使您的代码有效,它也仅适用于一个按钮,任何其他尝试使用相同样式的按钮都会失败。相反,您可以像这样使用
ContentTemplate
属性: -现在为按钮提供一个
DataTemplate
,它用于构造呈现按钮内容的子元素。因此,每个按钮都将构造自己独立的Image
控件实例。Its not a good idea to include UIElements such as
Image
in a style. Such an object is created only once when the style is put together during Xaml parsing. An important thing to understand about UIElements is that a single instance can only appear once in the Visual Tree. So even if your code worked it would only work for one button, any other button trying to use the same style would fail.Instead you can use the
ContentTemplate
property like this:-The button is now given a
DataTemplate
that it uses to construct the child element that renders the content of the button. Each button will therefore construct its own independent instance of anImage
control.您应该使用 x:Key 来命名您的 Style 元素,而不是 x:Name
You should use x:Key to name your Style element rather than x:Name
您的代码需要进行两处更改。
将
x:Name
更改为x:Key
,并在需要使用时引用它,使用StaticResource
。改变这个
对此,
看看对你有没有帮助!
Your code requires two changes.
Changed
x:Name
tox:Key
, And refer to it when you want to use it, usingStaticResource
.Change this
to this,
See if it helps you!