65.9K
CodeProject is changing. Read more.
Home

Simple Image Button in Silverlight

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (2 votes)

Jul 22, 2011

CPOL
viewsIcon

20331

Simple Image Button

Introduction

In this article we'll see how to create an custom image button by adding an image and textblock to the existing button control to derive our new ImageButton control

Using the Code

Create a new silverlight application. and add an folder called "Themes". Right click the created "Themes" Folder and Select "New item" and choose resource dictionary and name it as generic.xaml Set the Build Action of the file to Page - which is the default one.
 ....
<Style TargetType="Custom:MyButton">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="Custom:MyButton">
            <Grid x:Name="Root" Background="AliceBlue">
               <Grid.ColumnDefinitions>
                  <ColumnDefinition Width=".30*"/>
                  <ColumnDefinition Width=".70*"/>
               </Grid.ColumnDefinitions>
               <Image 
                  Source="/SilverlightApplication1;component/Images/exclamation1.png" 
                  Width="30"
                  Height="30" Grid.Column="0"></Image>
               <TextBlock Text="My Button" Grid.Column="1"
                  VerticalAlignment="Center"></TextBlock>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>
.....
Add a new class to the project which extends the Button In the constructor you have to assign the type of your class to DefaultStylekey. Which is more important otherwise your button won't show up the style declared in generic.xaml.

MyButton.cs:

public class MyButton : Button
    {
        public MyButton()
        {
            this.DefaultStyleKey = typeof(MyButton);
        }
    }
Just add reference to our control and we can use it like any other silverlight control

MainPage.xaml:

...
  <Grid x:Name="LayoutRoot" Background="White">
        <Custom:MyButton  Width="100" Height="30" Click="MyButton_Click">
        </Custom:MyButton>
  </Grid>
...

Points of Interest

We can control the visual state of the control by adding visual state manager to our generic.xaml