C#自定義WPF中Slider的Autotooltip模板
Slider控件有一個(gè)我比較喜歡的屬性"AutoToolTip",可以在拖動(dòng)的過程中顯示當(dāng)前刻度,然而這個(gè)刻度卻不支持模板定制,并且就連自定義格式也不行。這就大大的限制了它的使用范圍。網(wǎng)上有篇文章解決了這個(gè)問題,可以實(shí)現(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; } } }
使用起來也很簡(jiǎn)單。
<local:FormattedSlider AutoToolTipFormat="{}{0}% used" AutoToolTipPlacement="BottomRight" />
其實(shí)原理也不復(fù)雜,通過反射設(shè)置"_autoToolTip"變量,從而實(shí)現(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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#實(shí)現(xiàn)WPF項(xiàng)目復(fù)制和移動(dòng)文件夾
- C#中WPF顏色對(duì)話框控件的實(shí)現(xiàn)
- C# WPF開源UI控件庫(kù)MaterialDesign介紹
- C#?WPF數(shù)據(jù)綁定模板化操作的完整步驟
- C#?wpf?通過HwndHost渲染視頻的實(shí)現(xiàn)方法
- C# wpf簡(jiǎn)單顏色板的實(shí)現(xiàn)
- C# WPF實(shí)現(xiàn)的語(yǔ)音播放自定義控件
- C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標(biāo)
- c# wpf如何附加依賴項(xiàng)屬性
相關(guān)文章
C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例詳解
這篇文章主要介紹了C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例以及相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2019-08-08C#使用Aspose.Cells創(chuàng)建和讀取Excel文件
這篇文章主要為大家詳細(xì)介紹了C#使用Aspose.Cells創(chuàng)建和讀取Excel文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10一個(gè)狀態(tài)機(jī)的實(shí)現(xiàn)
本文主要介紹了C#實(shí)現(xiàn)一個(gè)狀態(tài)機(jī)的思路與方法,具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-02-02c#操作sqlserver數(shù)據(jù)庫(kù)的簡(jiǎn)單示例
這篇文章主要介紹了c#操作sqlserver數(shù)據(jù)庫(kù)的簡(jiǎn)單示例,需要的朋友可以參考下2014-04-04C#實(shí)現(xiàn)多線程編程的簡(jiǎn)單案例
這篇文章介紹了C#實(shí)現(xiàn)多線程編程的簡(jiǎn)單案例,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04