这篇文章介绍了C#自定义WPF中Slider的Autotooltip模板的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
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;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#自定义WPF中Slider的Autotooltip模板


基础教程推荐
猜你喜欢
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#中的Linq to JSON操作详解 2023-06-08
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C# 解析XML和反序列化的示例 2023-04-14
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity shader实现高斯模糊效果 2023-01-16