Search code examples
javaxamlwidthtextblock

Using Java, how to get the 'ActualWidth' of the text of a TextBlock and use it?


See subject title.

I have a method in Java that draws a TextBlock element:

public void drawTextBlock(String text) {
    Element textBlock = new Element("TextBlock", Ns.getDefaultNamespace());
    textBlock.setAttribute(new Attribute("Text", text));
}

However, the Width of the TextBlock must be exactly as wide as the width of the text I give to it.

How would this be done?


Solution

  • You don't need to set the width. Unless the HorizontalAlignment is Stretch (which is the default) The width of a TextBlock automatically adjusts to the size of the text it contains (as long as there is enough space to contain the TextBlock of course). So you just need to set the HorizontalAlignment to Left, Right or Center