Creating a custom button in XAML

The XAML language has a Button element, but for a Web application you could create your own custom version.

You could also makes use of the <input type="button"> element of HTML, but in this case the application will work only with a browser. To have buttons common to Web applications and desktop software, you have to create yours.

Drawing the shape

One takes again the code of the rectangle with the rounded corners:


One obtains the shape of the button below:

To embellish the button it is necessary to remove the color property and to open tag for a more elaborate design. When one thus transforms the property into tag, the color can be given with the SolidColorBrush tag:

    <SolidColorBrush Color="LightGray" />

The image remains the same one:

Now shaded colors are added with gradients, clear in top left corner, dark to the opposite corner:

    <LinearGradientBrush >
         <GradientStop Color="White" Offset="0.0" />
         <GradientStop Color="LightGray" Offset="0.20" />
         <GradientStop Color="Gray" Offset="0.9" />
         <GradientStop Color="LightGray" Offset="0.20" />

Adding a text

To add a text, which cannot be made inside a rectangle, one creates an inner Canvas and it is inside this Canvas where one will align the Rectangle and TextBlock.

        <Rectangle Canvas.Top="4" Canvas.Left="4" >
        <TextBlock Canvas.Left="14" Canvas.Top="6">

The button equipped now with a label:

Defining an interaction

To add a handling of user's actions, one creates JavaScript functions that are associated to the Canvas of our button.
When the mouse:
- is on the button (MouseEnter), a black edge appears,
- and it disappears when it leaves the surface (MouseLeave).
- When one clicks on the button (MouseLeftButtonDown), the button is shifted on the screen, some action is performed, a message is displayed in our example, then the button retrieves its normal aspect.
- When the mouse button is released (MouseLeftButtonUp), or after the execution of the action, the button takes again the normal position.


To shift the button on the page and to simulate a pressed button, the Canvas of the button, which contains both the rectangle and the text, is shifted.
For that, it will be necessary for us to use a new property, RenderTransform, which makes it possible to perform various transformations on an object, but all that interests us here, it is the translation of co-ordinates.
For that we give a name to the tag, "addoffset" which will be used in the JavaScript code.

           <TranslateTransform x:Name="addoffset" X="0" Y="0"/>

You can click on the button below:

Full source code

See also