Current size TextBlock runtime

0

Well, I have one question that is as follows. I'm creating a TextBlock at runtime with the following code:

TextBlock txtMensagem = new TextBlock();
txtMensagem.Text = texto.Trim();
txtMensagem.TextWrapping = TextWrapping.Wrap;
txtMensagem.Height = Double.NaN;
txtMensagem.Width = Double.NaN;
txtMensagem.MinWidth = 200;
txtMensagem.MaxWidth = 500;
txtMensagem.FontSize = 16;
txtMensagem.FontWeight = FontWeights.Bold;
txtMensagem.FontFamily = new FontFamily("Consolas");
txtMensagem.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtMensagem.Foreground = Brushes.Black;
txtMensagem.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtMensagem.Margin = new Thickness(15, 30, 0, 25);

After the TextBlock is created, I need to know the current size of the TextBlock. But the command txtMensagem.ActualWidth returns 0. In another project I did the following gambiarra:

gridMensagem.Children.Add(txtMensagem);
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
gridMensagem.Children.Remove(txtMensagem);

//Agora o ActualWidth Funciona
double tamanho = txtMensagem.ActualWidth;

This code I add on the grid, I give the 'DoEvents ()' command for the text to be drawn on the screen and then I remove it, so I can get the size it will occupy with the txtMensagem.ActualWidth command, The same code does not work on my new project.

Does anyone have any idea what I can do to get the size of the TextBlock?

Note: I'm using WPF

Thank you.

    
asked by anonymous 24.04.2015 / 18:17

1 answer

0

In the link that the ramaral passed me I found the following piece of code that worked. I do not quite understand how it works but it worked.

TextBlock txtMensagem = new TextBlock();
txtMensagem.Text = texto.Trim();
txtMensagem.TextWrapping = TextWrapping.Wrap;
txtMensagem.Height = Double.NaN;
txtMensagem.Width = Double.NaN;
txtMensagem.MinWidth = 200;
txtMensagem.MaxWidth = 500;
txtMensagem.FontSize = 16;
txtMensagem.FontWeight = FontWeights.Bold;
txtMensagem.FontFamily = new FontFamily("Consolas");
txtMensagem.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtMensagem.Foreground = Brushes.Black;
txtMensagem.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtMensagem.Margin = new Thickness(15, 30, 0, 25);

//Codigo retirado do comentário do ramaral
txtMensagem.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
txtMensagem.Arrange(new Rect(txtMensagem.DesiredSize));

//Agora o ActualWidth Funciona
double tamanho = txtMensagem.ActualWidth;

Placing these two lines before calling ActualWidth works.

    
28.04.2015 / 18:27