Slider控制項有一個我比較喜歡的屬性"AutoToolTip",可以在拖動的過程中顯示當前刻度,然而這個刻度卻不支援模板定製,並且就連自訂格式也不行。這就大大的限制了它的使用範圍。網上有篇文章Modifying the auto tooltip of a Slider(由於wordpress被和諧了,這個地址是無法訪問的)解決了這個問題,可以實現自訂顯示格式
代碼如下:
Code
/**//// <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;
}
}