Technical Blog

# Developing a (very) Lookless Silverlight Radial Gauge Control

, 19 Aug 2010 CPOL
 Rate this:
Development of a lookless radial gauge control

This blog post describes the development of a lookless radial gauge control. In this post, I will explore the use of an attached view model in order to move view specific properties and logic out of the control code in order to give a truly lookless control.

Today, I had to get up far too early in order to catch an early morning flight to Copenhagen with a connection in Amsterdam. What to do for the six hours I would be travelling? Armed with a netbook and Visual Studio 2010 Express, I thought it would be fun to have a go at developing a Silverlight gauge control. I know that there are already one or two free ones out there, with a decent looking one available on CodeProject, however, it still felt like a good way to pass the time!

In order to make things a little more challenging, I wanted to create a control that was truly lookless. So, what do I mean by this? Firstly, a gauge control in its simplest sense displays the location of some indicator between a maximum and minimum value. There is nothing inherently circular about a gauge, thermometers are a good example of a linear gauge. So, I don’t want any ‘circular’ logic in the control itself. Secondly, custom controls often have certain expectations about the presence of named elements within their template. By this, I mean that the template must contain, for example, a `Path `element called ‘`needle`’ which the control code will manipulate (the gauge published in the CodeProject article above requires the presence of four named elements in the template). This forces certain constraints regarding how the control can be templated, this is really lookless, is it?

The following example shows the gauge control which I created, and the rest of this post describes the implementation:

[See this control in action on my blog.]

```<local:GaugeControl Value="65" Width="200" Height="200"
Maximum="100" Minimum="50"
x:Name="gauge">
<local:GaugeControl.QualitativeRange>
<local:QualitativeRanges>
<local:QualitativeRange Color="Yellow" Maximum="75"/>
<local:QualitativeRange Color="Orange" Maximum="90"/>
<local:QualitativeRange Color="Red" Maximum="100"/>
</local:QualitativeRanges>
</local:GaugeControl.QualitativeRange>
</local:GaugeControl>```

## The Starting Point

The first step was to create a Gauge custom control with Value, Maximum and Minimum dependency properties. The only logic defined within the control itself is to set the `DataContext `of the root visual element to the control instance itself. This is quite a common approach to control design, allowing elements within the template to bind to the control properties:

```public override void OnApplyTemplate()
{
base.OnApplyTemplate();

Grid root = GetTemplateChild("LayoutRoot") as Grid;
root.DataContext = this;
}```

The first thing I added to the control template was the ‘face’ of the radial gauge. This is simply an Ellipse with a pretty gradient fill and stroke:

```<!--<span class="code-comment"> dial background and outer border --></span>
<Ellipse Stretch="Fill" StrokeThickness="8">
<Ellipse.Fill>
</Ellipse.Fill>
<Ellipse.Stroke>
</Ellipse.Stroke>
</Ellipse>```

The next thing I added to the control was a needle. This is rendered using a simple `Path `with a `LinearGradient `in order to give it some sense of depth. I want the needle to have a length of approximately 70% of the gauge’s radius, a simple way to achieve this is to construct it within a Grid that uses ‘star’ widths / heights to provide a proportional layout and configure the `Path `to stretch to fill the cell it occupies:

```<!--<span class="code-comment"> the needle path --></span>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="7*"/>
<RowDefinition Height="10*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>

<Path Stretch="Uniform"
Grid.Row="1" Grid.ColumnSpan="2"
HorizontalAlignment="Center"
Stroke="Black" StrokeThickness="0.5"
Data="M 0,0 l 10,60 l -10, 40 l -10 -40">
<Path.Fill>
</Path.Fill>
</Path>
</Grid>```

Here, you can see how the needle is scaled by its parent Grid:

Rotating the needle to reflect the current Gauge Value is achieved quite simply via `RotateTransform`. However, this needs to be converted into a rotation angle which depends on the Gauge Maximum /Minimum values together with the overall angle of sweep on the gauge. I initially approached this problem by applying bindings via value converters and multibindings, however I found myself repeating the same conversion logic in numerous places within the template in order to render the ticks, etc… Ideally, the angle of rotation would be something that the template could bind to. The template `DataContext `is bound to the Gauge control itself, however as stated earlier, I do not want ‘circular’ concepts to leak into the control.

## An Attached View Model

The solution I came up with for this problem was to create a view model that lives entirely within the control template that acts as an adapter for the Gauge, supplementing its properties with the needed ‘circular’ concepts. In keeping with my aims, I could not instantiate this view model within the Gauge control itself, so instead, it is created via an attached behaviour within the control template:

```<Style TargetType="local:GaugeControl">
<Setter Property="FontSize" Value="10"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:GaugeControl">
<Grid x:Name="LayoutRoot" >
<Grid>
<!--<span class="code-comment"> attached the view model --></span>

<!--<span class="code-comment"> ... control template goes here ...  --></span>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>```

The view model defines the `Attach `property and in its change handler performs the logic required to bind to the `DatatContext `of the parent (which is the Gauge control itself), and set itself as the `DataContext `of the `Grid `to which it is being attached. This allows the rest of the template to bind to properties of the `RadialGaugeControlViewModel`.

```public class RadialGaugeControlViewModel : FrameworkElement, INotifyPropertyChanged
{
#region Attach attached property

public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach", typeof(object),

{
}

public static void SetAttach(DependencyObject d, RadialGaugeControlViewModel value)
{
d.SetValue(AttachProperty, value);
}

/// <span class="code-SummaryComment"><summary>
</span>  /// Change handler for the Attach property
/// <span class="code-SummaryComment"></summary>
</span>  private static void OnAttachChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
Grid targetElement = d as Grid;

}

/// <span class="code-SummaryComment"><summary>
</span>  /// Handle the Loaded event of the Grid to enable the attached
/// view model to bind to properties of the Grid Parent element
/// <span class="code-SummaryComment"></summary>
</span>  static void Grid_Loaded(object sender, RoutedEventArgs e)
{
FrameworkElement targetElement = sender as FrameworkElement;
FrameworkElement parent = targetElement.Parent as FrameworkElement;

// use the attached view model as the DataContext of the element it is attached to
targetElement.DataContext = attachedModel;

// bind the DataContext of the view model to the DataContext of the parent.
new Binding("DataContext")
{
Source = parent
});
}
}```

It is now possible to expose a property on the view model which provides the Gauge Value as an angle:

```public double ValueAngle
{
get
{
if (Gauge == null)
return 0.0;

return ValueToAngle(Gauge.Value);
}
}

private double ValueToAngle(double value)
{
double minAngle = -150;
double maxAngle = 150;
double angularRange = maxAngle - minAngle;

return (value - Gauge.Minimum) / (Gauge.Maximum - Gauge.Minimum) *
angularRange + minAngle;
}```

This can then be bound to in the template in order to rotate the needle. For an extra ‘flourish’, a drop shadow is also added to the needle which binds to this same rotation angle in order to give a subtle ‘3D’ effect:

```<Path Stretch="Uniform"
Grid.Row="1" Grid.ColumnSpan="2"
HorizontalAlignment="Center"
Stroke="Black" StrokeThickness="0.5"
Data="M 0,0 l 10,60 l -10, 40 l -10 -40"
RenderTransformOrigin="0.5,1">
<Path.RenderTransform>
<!--<span class="code-comment"> rotate the needle --></span>
<RotateTransform Angle="{Binding Path=ValueAngle}"/>
</Path.RenderTransform>
<Path.Fill>
</Path.Fill>
<Path.Effect>
Opacity="0.6"
</Path.Effect>
</Path>```

The gauge control needs to have tick marks and labels rendered around the dial face at regularly spaced intervals between the Maximum and Minimum values. Here, the view model comes into its own by providing a list of ‘`Tick`’ value objects, each of which provide the view with the required information to render tick marks and their labels:

```public IEnumerable<Tick> MajorTicks
{
get
{
if (Gauge == null)
yield break;

double tickSpacing = (Gauge.Maximum - Gauge.Minimum) / 10;
for (double tick = Gauge.Minimum; tick <= Gauge.Maximum; tick += tickSpacing)
{
yield return new Tick()
{
Angle = ValueToAngle(tick),
Value = tick.ToString("N0"),
Parent = this
};
}
}
}

public class Tick
{
public double Angle { get; set; }
public string Value { get; set; }
public RadialGaugeControlViewModel Parent { get; set; }
}```

The XAML which renders the major tick marks uses an `ItemsControl `to create each tick instance:

```<!--<span class="code-comment"> major ticks --></span>
<ItemsControl ItemsSource="{Binding Path=MajorTicks}"
VerticalAlignment="Center" HorizontalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas></Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse Fill="Black" Width="8" Height="8">
<Ellipse.RenderTransform>
<TransformGroup>
<!--<span class="code-comment"> centre the ellipse --></span>
<TranslateTransform X="-4" Y="-4"/>
<!--<span class="code-comment"> offset to the edge of the gauge --></span>
<TranslateTransform X="0"
Y="{Binding Path=Parent.GridHeight,
Converter={StaticResource ScaleFactorConverter},
ConverterParameter=-0.37}"/>
<!--<span class="code-comment"> rotate --></span>
<RotateTransform Angle="{Binding Angle}"/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>```

As you can see, each tick is simply an ellipse. The clever part is how each Ellipse is transformed to position it appropriately. It is first centred to make subsequent transforms a little simpler, it is then translated y an offset which moves it to the edge of the gauge face. The offset factor is computed as some fraction of the overall size of the gauge control. In order to achieve this, I reluctantly had to angle `SizeChanged `events on the template `Grid `in order to expose its `ActualHeight `/ `ActualWidth`, this is because `ElementName `binding on these properties appears to be broken.

On attachment, the view model handles `SizeChanged `events as follows:

```/// <span class="code-SummaryComment"><summary>
</span>/// Handle SizeChanged events from the grid so that we can inform elements
/// of changes in the ActualHeight / ActualWidth
/// <span class="code-SummaryComment"></summary>
</span>private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
OnPropertyChanged("GridHeight");
OnPropertyChanged("GridWidth");

Grid.Clip = new EllipseGeometry()
{
Center = new Point(_grid.ActualWidth / 2, _grid.ActualHeight / 2)
};
}

public double GridWidth
{
get { return _grid.ActualWidth; }
}

public double GridHeight
{
get { return _grid.ActualHeight; }
}```

Adding tick labels and minor tick marks both use a simple variation on the above described approach:

I also added a ‘qualitative value’ range which renders a colour coded band beneath the needle. Again, this uses variations on the same approach, with the view model adapting the properties of the Gauge control and the template binding to these properties, together with the Grid size information in order to provide any required scaling.

The last flourish was to add a ‘glass’ effect to the Gauge. This was ‘borrowed’ directly from this fantastic CodeProject article on creating ‘round glassy buttons’.

The finished Gauge is shown below, where its value is bound to a Slider control:

[See this control in action on my blog.]

## Conclusions

I am pretty happy with how this Gauge control turned out, visually I think it looks pretty good. I am also happy that I have succeeded in my initial aim of making it completely lookless. The attached view model within the control template is an interesting approach that moves view specific concepts (in this case, angular properties) into the view, which is where they belong.

This radial Gauge control could certainly be improved to allow a more flexible scale calculation. Also, the `RadialGaugeControlViewModel `could also expose some of the view specific properties such as the radial sweep angle (currently hard-coded to 300 degrees) allowing them to be set in the template. For now, I think I will leave this control as it is.

Tomorrow I am on another early flight, this time heading back home. I might take this as an opportunity to provide a view for this control making use of a different attached view model.

(Apologies for the lack of project structure, this code was written using VS 2010 Express).

Regards, Colin E.

## Share

Architect Scott Logic
United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

-

 First Prev Next
 My vote of 5 NetDave 8-Dec-10 5:06
 Adding the Control to the Visual Tree integragreg 29-Aug-10 6:20
 Last Visit: 31-Dec-99 19:00     Last Update: 26-Nov-14 21:04 Refresh 1