自訂WPF中Slider的Autotooltip模板

來源:互聯網
上載者:User

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;
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.