#1,161 – Using Custom Circular Progress Shape in Control Template

In the previous example, we created a custom circular progress shape and then composed it along with a TextBlock to get a labeled circular progress control.

The other approach that we could take is to just create a new control template containing our circular progress shape and a TextBlock and then use that new template as the control template for a standard ProgressBar.

Assuming that we start with the earlier code for CircularProgress, we compose the template and use it as follows:

	<Window.Resources>
        <loc:DoubleToPctConverter x:Key="dblToPct"/>
		<Style x:Key="pbarCircularStyle" TargetType="{x:Type ProgressBar}">
			<Setter Property="Foreground" Value="#01D328"/>
            <Setter Property="Maximum" Value="100"/>
            <Setter Property="Height" Value="100"/>
            <Setter Property="Width" Value="100"/>
            <Setter Property="Template">
				<Setter.Value>
					<ControlTemplate TargetType="{x:Type ProgressBar}">
						<Grid x:Name="TemplateRoot" SnapsToDevicePixels="true">
                            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
                                       FontSize="32" Foreground="DarkGray"
                                       Text="{TemplateBinding Value, Converter={StaticResource dblToPct}}" />
                            <loc:CircularProgress Stroke="{TemplateBinding Foreground}"
                                                  Value="{TemplateBinding Value}"/>
						</Grid>
					</ControlTemplate>
				</Setter.Value>
			</Setter>
		</Style>
	</Window.Resources>

    <StackPanel>
        <Grid>
			<ProgressBar Style="{DynamicResource pbarCircularStyle}"
						 Value="{Binding PctComplete}"
						 Margin="10"/>
        </Grid>
        <Button Content="Start Timer" Click="Button_Click"
                HorizontalAlignment="Center"
                Padding="12,7"/>
    </StackPanel>

1161-001

For completeness, here’s the source code for our value converter:

    public class DoubleToPctConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string result = "";
            double d = (double)value;
            result = string.Format("{0}%", d);

            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }