Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a labels width before it is rendered in WPF

Tricky one to explain this. I have a custom built properties grid. The left hand column has the property labels. Sometimes depending on the property, I want a little elipsis button to show the user that they can launch a dialog. I want the buttons to be inline vertically to make the UI look neat. The labels vary in width depending on the name of the property "onEnterPressed" or "upLink" for example.

If I add the elipses button alone and use a margin like so ...

elipsisButton.Margin = new Thickness(135, 0, 0, 0);

135 from the left is exactly where I want to place the button.

I was hoping to be able to do something like

Label newLabel = new System.Windows.Controls.Label();
newLabel.Content = anInfo;
aPanel.Children.Add(newLabel);
elipsisButton.Margin = new Thickness(135 - newLabel.Width, 0, 0, 0);

It would appear however, that the label doesn't get a width until it's been rendered on screen so I can't find out what size margin to add to my elipsis button. Any ideas?

like image 454
DrLazer Avatar asked Jul 08 '10 14:07

DrLazer


1 Answers

You can call the Measure() method in order to ask the control the size it needs to be displayed:

var l = new Label() { Content = "Hello" };
l.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

Size s = l.DesiredSize;

And then use the value of the DesiredSize property.

like image 135
japf Avatar answered Oct 14 '22 05:10

japf