WPF Buttons with Polygon Graphics


Are you working on a WPF program that requires buttons? Are those buttons requiring symbols instead of words? For example, do you need buttons for forward and back? How about stop and pause or play?

One way to do this is to use a png (or other type such as gif) graphic file and use Image in XAML. This post discusses a different way. Here we’ll use XAML Shapes instead of graphic files. A Shape is a basic 2D drawing that combines a Geometry with a Pena and Brush. WPF provides six classes that derive from the abstract System.Windows.Shapes.Shape class:

  • Rectangle
  • Ellipse
  • Line
  • Polyline
  • Polygon
  • Path

The Polygon Shape

Below is a screenshot of a running WPF Windows program developed with XAML in Visual Studio. The user has placed the mouse over the left arrow and the button’s blue background is showing.

Below is the listing that shows the above screenshot (except for the background). The listing is XAML code inside of a WPF project. The code below is inside of a horizontal StackPanel, but that code is not shown for brevity.

<Button x:Name="btnBack" FontSize="14" Click="BtnBack_Click" Margin="20,5,5,5" 
        Background="Transparent" BorderThickness="0">
    <Polygon Points="18,0 0,10 18,20" Fill="DarkSlateGray" />
</Button>
<Label x:Name="lblDate" FontSize="14" Margin="15,5,5,5.4" Width="139" VerticalAlignment="Center" 
        HorizontalAlignment="Center">November 24, 2020</Label>
<Button x:Name="btnForward" FontSize="14" Click="BtnForward_Click" Margin="5,5,5,5" 
        Background="Transparent" BorderThickness="0">
    <Polygon Points="0,0 18,10 0,20" Fill="DarkSlateGray" />
</Button>

The polygon has three points that are used to build the triangle. They are x,y points where 0,0 is the upper left corner. x runs horizontally and y runs vertically. The units are pixels. The Fill is the color of the inside of the polygon. We set the Background to Transparent and the BorderThickness to zero to make the border invisible.