I'm using Silverlight 4. I have a button:
&开发者_如何学Pythonlt;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?
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:-
<Style x:Key="AddButton" TargetType="Button">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="/PlumPudding;component/Images/appbar.add.rest.png" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Click="addTopicButton_Click" Style="{StaticResource AddButton}" />
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 an Image
control.
You should use x:Key to name your Style element rather than x:Name
Your code requires two changes.
Changed
x:Name
tox:Key
, And refer to it when you want to use it, usingStaticResource
.Change this
<Setter.Value> <Image Source="whatever..." /> </Setter.Value>
to this,
<Setter.Value> <DataTemplate> <Image Source="whatever..." /> </DataTemplate> </Setter.Value>
See if it helps you!
精彩评论