垃圾站 生活小记 C#自定义WPF中Slider的Autotooltip模板

C#自定义WPF中Slider的Autotooltip模板

Slider控件有一个我比较喜欢的属性”AutoToolTip”,可以在拖动的过程中显示当前刻度,然而这个刻度却不支持模板定制,并且就连自定义格式也不行。这就大大的限制了它的使用范围。

C#自定义WPF中Slider的Autotooltip模板插图

网上有篇文章解决了这个问题,可以实现自定义显示格式!

代码如下:

/// <summary>
/// A Slider which provides a way to modify the 
/// auto tooltip text by using a format string.
/// </summary>
public class FormattedSlider : Slider
{
private ToolTip _autoToolTip;
private string _autoToolTipFormat;

/// <summary>
/// Gets/sets a format string used to modify the auto tooltip's content.
/// Note: This format string must contain exactly one placeholder value,
/// which is used to hold the tooltip's original content.
/// </summary>
public string AutoToolTipFormat
{
get { return _autoToolTipFormat; }
set { _autoToolTipFormat = value; }
}

protected override void OnThumbDragStarted(DragStartedEventArgs e)
{
base.OnThumbDragStarted(e);
this.FormatAutoToolTipContent();
}

protected override void OnThumbDragDelta(DragDeltaEventArgs e)
{
base.OnThumbDragDelta(e);
this.FormatAutoToolTipContent();
}

private void FormatAutoToolTipContent()
{
if (!string.IsNullOrEmpty(this.AutoToolTipFormat))
{
this.AutoToolTip.Content = string.Format(
this.AutoToolTipFormat, 
this.AutoToolTip.Content);
}
}

private ToolTip AutoToolTip
{
get
{
if (_autoToolTip == null)
{
FieldInfo field = typeof(Slider).GetField(
"_autoToolTip",
BindingFlags.NonPublic | BindingFlags.Instance);

_autoToolTip = field.GetValue(this) as ToolTip;
}

return _autoToolTip;
}
}
}

使用起来也很简单。

<local:FormattedSlider
 AutoToolTipFormat="{}{0}% used"
AutoToolTipPlacement="BottomRight" />

其实原理也不复杂,通过反射设置”_autoToolTip”变量,从而实现自定义AutoToolTip格式

private ToolTip AutoToolTip
{
get
{
if (_autoToolTip == null)
{
FieldInfo field = typeof(Slider).GetField(
"_autoToolTip",
BindingFlags.NonPublic | BindingFlags.Instance);

_autoToolTip = field.GetValue(this) as ToolTip;
}

return _autoToolTip;
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇
下一篇
联系我们

联系我们

返回顶部