Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Image Button in Silverlight

0.00/5 (No votes)
22 Jul 2011 1  
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:

C#
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here