user2408987
user2408987

Reputation: 101

display tooltip when text exceeds max width in the textbox

i have the below text box control if the text in the textbox exceeds the max width then we should display tooltip.

<TextBox Name="ClientAgreementNumberHCCText" 
                         TextAlignment="Left" 
                         TextWrapping="NoWrap" 
                         Text=" {Binding Text,Mode=OneWay}"/>

Note that i don't want to use the wrap of the textbox. how can i do this?

Upvotes: 0

Views: 1153

Answers (2)

Jawahar
Jawahar

Reputation: 4885

This is possible by manually measuring the textBox with maximum size and compare the Desired Size with Actual Size. I added the following code in textChanged event of TextBox and it works fine.

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox.Measure(new Size(Double.MaxValue, Double.MaxValue));
        var width = textBox.DesiredSize.Width;

        if (textBox.ActualWidth < width)
        {
            ToolTipService.SetToolTip(textBox, textBox.Text);
        }
        else
        {
            ToolTipService.SetToolTip(textBox, null);
        }
    }

More detail on this.

Upvotes: 1

peter
peter

Reputation: 15089

I think you want to use TextBox.GetRectFromCharacterIndex which will give you a Rect where the width is the width of your text.

You can calculate the rectangle and get the width on the fly whenever the binded text changes. You can compare the width to the width of your TextBox and see if the text is too long, and based on that set a tooltip or not. (Consider checking if you only need the width, or also need to consider paddings and margins)

here is my source: http://dedjo.blogspot.de/2007/03/text-length-measurement-it-really-easy.html

Upvotes: 0

Related Questions