C#自定義WPF中Slider的Autotooltip模板
更新時間:2022年06月16日 16:50:28 作者:天方
這篇文章介紹了C#自定義WPF中Slider的Autotooltip模板的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
Slider控件有一個我比較喜歡的屬性"AutoToolTip",可以在拖動的過程中顯示當前刻度,然而這個刻度卻不支持模板定制,并且就連自定義格式也不行。這就大大的限制了它的使用范圍。網上有篇文章解決了這個問題,可以實現(xiàn)自定義顯示格式
代碼如下:
/// <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"變量,從而實現(xiàn)自定義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#通過PInvoke調用c++函數(shù)的備忘錄的實例詳解
這篇文章主要介紹了C#通過PInvoke調用c++函數(shù)的備忘錄的實例以及相關知識點內容,有興趣的朋友們學習下。2019-08-08C#使用Aspose.Cells創(chuàng)建和讀取Excel文件
這篇文章主要為大家詳細介紹了C#使用Aspose.Cells創(chuàng)建和讀取Excel文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10c#操作sqlserver數(shù)據(jù)庫的簡單示例
這篇文章主要介紹了c#操作sqlserver數(shù)據(jù)庫的簡單示例,需要的朋友可以參考下2014-04-04