WPF/Silverlight Slider control display tick numbers

10,043

I believe the best way to do this is to create a custom TickBar control and override the Rendering of the ticks. Here is one way:

public class NumberedTickBar : TickBar
  {
    protected override void OnRender(DrawingContext dc)
    {

      Size size = new Size(base.ActualWidth,base.ActualHeight);
      int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) + 1;
      if((this.Maximum - this.Minimum) % this.TickFrequency == 0)
        tickCount -= 1;
      Double tickFrequencySize;
      // Calculate tick's setting
      tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
      string text = "";
      FormattedText formattedText = null;
      double num = this.Maximum - this.Minimum;
      int i = 0;
      // Draw each tick text
      for(i = 0;i <= tickCount;i++)
      {
        text = Convert.ToString(Convert.ToInt32(this.Minimum + this.TickFrequency * i),10);

        formattedText = new FormattedText(text,CultureInfo.GetCultureInfo("en-us"),FlowDirection.LeftToRight,new Typeface("Verdana"),8,Brushes.Black);
        dc.DrawText(formattedText,new Point((tickFrequencySize * i),30));

      }
    }
  }

Then you'll have to create a custom style for your slider that uses your new Tickbar instead of the default tickbar.

If you are not sure how to create a style for a slider you can start with the windows example here. It's a very sophisticated one.

Then the only thing left to do is to replace the Top Tickbar with your new custom one. Basically change:

<TickBar Name="TopTick" SnapsToDevicePixels="True" Placement="Top" Fill="{StaticResource GlyphBrush}" Height="4" Visibility="Collapsed" />

to this:

<local:NumberedTickBar Name="TopTick" Margin="5,0,10,0" SnapsToDevicePixels="True" Grid.Row="0" Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Visibility="Collapsed"/>

The margin is important because that will ensure that your text is in the right place.

Your slider will be on the top with ticks just below it. A row of text will be displayed below the ticks.

Share:
10,043
Mitch
Author by

Mitch

Updated on June 05, 2022

Comments

  • Mitch
    Mitch almost 2 years

    I'm using a WPF Slider control (I'm guessing the Silverlight version is similar) that's set to horizontal and has a Min Value of 0 and a Max Value of 5.

    I'd like to display the values 0 - 5 below the tick marks to make it a bit more obvious which value the thumb is currently pointing to.

    Is this possible and has anybody managed to achieve this?