这篇文章介绍了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#通过GET/POST方式发送Http请求 2023-04-28
- 京东联盟C#接口测试示例分享 2022-12-02
- 使用c#从分隔文本文件中插入SQL Server表中的批量数据 2023-11-24
- c#读取XML多级子节点 2022-11-05
- C#中类与接口的区别讲解 2023-06-04
- Unity shader实现多光源漫反射以及阴影 2023-03-04
- C# – NetUseAdd来自Windows Server 2008和IIS7上的NetApi32.dll 2023-09-20
- C# Winform实现石头剪刀布游戏 2023-01-11
- C#集合查询Linq在项目中使用详解 2023-06-09
- c#中利用Tu Share获取股票交易信息 2023-03-03