WPF/Silverlight Slider 控件显示刻度数 [英] WPF/Silverlight Slider control display tick numbers
问题描述
我正在使用一个 WPF Slider 控件(我猜 Silverlight 版本是类似的),它设置为水平,最小值为 0,最大值为 5.
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.
我想在刻度线下方显示 0 - 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?
推荐答案
我认为最好的方法是创建一个自定义的 TickBar 控件并覆盖刻度的渲染.这是一种方法:
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));
}
}
}
然后,您必须为使用新的 Tickbar 而不是默认的 Tickbar 的滑块创建自定义样式.
Then you'll have to create a custom style for your slider that uses your new Tickbar instead of the default tickbar.
如果您不确定如何为滑块创建样式,您可以从 Windows 示例开始这里. 这是一个非常复杂的.
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.
那么剩下要做的唯一一件事就是用您的新自定义替换顶部 Tickbar.基本改变:
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" />
为此:
<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.
这篇关于WPF/Silverlight Slider 控件显示刻度数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!