Search code examples
c#wpfbackgroundsliderdrawingbrush

WPF - Is the offset, when working on a slider, defined anywhere?


I've been working on a proper slider for my C# WPF project.

I wanted to create a slider, with a background that indicates different parts of the process, by adding a different color to each section on the slider. Furthermore I wanted to add small indicators (like the default ticks, but custom shape and irregular position) to the background.

I achived this by creating a drawing brush and adding correspondingly colored rectangles. This seemed to work fine, but a small distortion was still present, so I investigated further and realized the following:

With slider.ActualWidth I get the width of the whole widget. So in order to create a background covering the actual "slider" part, I'll have to be aware of the distance from the widget to the actual slider. (See image)

enter image description here

I measured the distance in a very small window, in fullscreen and stretched on two screens. It seems this distance is always 5 pixels. I tried google and looked through the info WPF provides on its pages, but either I read over it, or there is no information on this.

Can I be sure this distance is always 5 pixels ? In there any place such information is kept ? Is there maybe another way, to determine the size of the slider itself?


Solution

  • Assuming you haven't tinkered with the Slider template you can just walk down the visual tree and check the ActualWidth of the track:

    Border b = VisualTreeHelper.GetChild(slider, 0) as Border;
    Grid g = VisualTreeHelper.GetChild(b, 0) as Grid;
    Border track = VisualTreeHelper.GetChild(g, 2) as Border;
    Console.WriteLine("Track ActualWidth: " + track.ActualWidth);