Changing the Background on a Button

A recent question in the Windows Phone Development Forums asking for the XAML to display a background image in a button when it is pressed. Generating the XAML to do this is pretty easy (if you know how!). While the request was for the XAML for doing this I thought the instructions for producing the XAML to do this are of great value.

Open expressions blend and start a new project. In your project add a new button. Right-click on the button and select “Edit template”->”Edit Copy” You will be prompted for the name of the new button style that we are creating (call it what you want) and whether the template will be defined in the document (page) or defined globally for the application. If you only plan on using the style in one page then it’s fine to define it within the document. In general you are probably going to use your style on more than one page. In either case for this exercise select the option to create the style within the document.

Switch to code view so that we can edit the XAML. Towards the top of your document you will see a style defined with the name you gave to it. Scroll down within the style until you find the construct with a ContentControl enveloped within a Border element. It will look like the following.

<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" 
            BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" 
            CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
     <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" 
                             Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" 
                             HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                             Padding="{TemplateBinding Padding}" 
                            VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>

We are going to make most our changes here. We need to place an image within this border element. It is going to be behind the content and so it will have to appear before the ContentControl element. The Border element can only have one child so we will need to make a Grid the Border‘s direct child and then place the Image element and ContentControl element within the Grid. The Image attribute will need to have a name and it will need to have its Opacity set to zero since the image usually will not be visible. The resulting XAML will look like the following.

<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
	<Grid>
		<Image x:Name="BackgroundImage" Source="/Background.png" 
                            Stretch="Fill" VerticalAlignment="Bottom" Opacity="0" />
		<ContentControl x:Name="ContentContainer" 
                                       ContentTemplate="{TemplateBinding ContentTemplate}" 
                                       Content="{TemplateBinding Content}" 
                                       Foreground="{TemplateBinding Foreground}" 
                                       HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                       Padding="{TemplateBinding Padding}" 
                                       VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
	</Grid>
</Border>

Almost done! There’s only a couple of things left. We want the image to be visible when the user is pressing the button. Scroll up within the template and you’ll find several VisualStateGroup elements defined. This area contains the changes and transitions that need to occur on the button when certain things happen such as the button going to a disabled state, loosing or gaining focus, and so on. We are interested in changes that occur in the pressed state. Within the VisualState named Press is a StoryBoard containing several animations. We need to add one more animation that changes the opacity of our button. As the last child of the StoryBoard element add the following.

<DoubleAnimation To="100" Duration="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundImage" />

Now if you run the project you’ll see the image show up in the button any time you press it, and disappear when ever you release it. Now how do you use this in another project? If you copy the Style element from this project and place it as a resource within your other projects it will be readily available for you (just make sure that your image source also appears in your target project). The style can be applied to a button through setting the buttons style.

<Button  Style="{StaticResource MyCustomButton}"/>

If you want to see what my entire style looks like here it is.

<Style x:Key="MyCustomButton" TargetType="Button">
	<Setter Property="Background" Value="Transparent"/>
	<Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
	<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
	<Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
	<Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
	<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
	<Setter Property="Padding" Value="10,3,10,5"/>
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="Button">
				<Grid Background="Transparent">
					<VisualStateManager.VisualStateGroups>
						<VisualStateGroup x:Name="CommonStates">
							<VisualState x:Name="Normal"/>
							<VisualState x:Name="MouseOver"/>
							<VisualState x:Name="Pressed">
								<Storyboard>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<DoubleAnimation To="100" Duration="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundImage" />
								</Storyboard>
							</VisualState>
							<VisualState x:Name="Disabled">
								<Storyboard>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
									</ObjectAnimationUsingKeyFrames>
								</Storyboard>
							</VisualState>
						</VisualStateGroup>
					</VisualStateManager.VisualStateGroups>
					<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
						<Grid>
							<Image x:Name="BackgroundImage" Source="/Background.png" Stretch="Fill" VerticalAlignment="Bottom" Opacity="0" />
							<ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
						</Grid>
					</Border>
					
				</Grid>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.