简体   繁体   中英

Resizing Labels

I have a chart in WPF with a lot of labels. The text on these labels is dynamically loaded and subject to change. If I set the width just to auto, then these labels may overlap, which makes the text unreadable.

The chart support multiple sizes, so if it gets larger, then the bars are re sized and there is more space for text. Now I want to adjust the text to the space which is available. If it gets too small, I don't want to display the label anymore (a tooltip is available, so the user still gets the required information). Consider the string "Case 1, blah blah", there is probably not enough space to display the whole string, but just the first word. In this case I want the string to be "Case 1..", with .. indicating that there is some more information in the tooltip.

I can determine the length available for the string. But how can I determine the space a single letter will take? Of course I could also just re size the label, but then it would just cut off the string anywhere which is probably not helpful for the user (and looks ugly).

Any ideas?

If you can use TextBlocks instead of labels then they have a TextTrimming property which will do this for you to either the nearest character or the nearest word.


While you seem happy with the TextTrimming property, I'll edit this to add that the TextBox control has a GetRectFromCharacterIndex method that would allow you to find out the size on screen of one or more characters as long as the font settings matched your label. This might be useful if you wanted to trim at specific places in the label rather than the nearest character / word.

Not an expert in WPF, but I would think that you'll need to do this in code rather than XAML.

Start by obtaining the actual pixel width of the space available for the text. Then look at the character set, dot pitch etc. utilised on the XAML front end and from there calculate the pixel width required per character.

You could also look at changing the character sizes as well as reducing the label length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM