0
Guys, I have a question that is the following. I am 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 this created Textblock I need to know the current size it has become. Put 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, give the command 'Doevents()' 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 command txtMensagem.ActualWidth
, but the same code does not work in my new project.
Does anyone have any idea what I can do to get the size of Textblock?
Note: I am using WPF
Grateful.
See if this helping.
– ramaral
Dude, almost hehehe... this gives me the size of the text(Sting), but in my case I would need the size of Textblock. But you could do a trick here, because the size of Textblock will always be between 200 and 500, so if you come back smaller than 200 I consider 200 and if you come back bigger than 500 I consider 500 :)
– Gustavo Freitas