Templating the background of a Button
I have a custom button as shown be开发者_运维技巧low, and i want to change the text color and image source in the pressed state.
<Button Background="#FFC17C7C" Style="{StaticResource CustomButton}">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center" Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="hello" />
<Image Source="Background.png" />
</StackPanel>
</Button>
If you can provide me with a simple example or useful links to solve this kind of problems, I'd be thankful.
First of all, you can't change the source of the content of a Button like that. You have to redefine the Button's Template, and the name the image something like PART_Image, so you can access it from the VisualState.
Now, if you want to be able to specify both backgrounds directly in the XAML, rather than in the template, you need to implement a custom UserControl inherting from Button.
But if you don't, you could simply use a ImageBrush to paint the background.
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<ImageBrush ImageSource="Pressed.png" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
And then, likewise, change the button definition, if you also want a image for the non-pressed state.
<Button Style="{StaticResource CustomButton}">
<Button.Background>
<ImageBrush ImageSource="NotPressed.png" />
</Button.Background>
<Button.Content>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="hello" />
</StackPanel>
</Button.Content>
</Button>
精彩评论