<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBox Name="TextBox1" HorizontalAlignment="Left" PreviewKeyUp="TextBox_PreviewKeyUp"></TextBox>
</StackPanel>
</Grid>
</Window>
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox1.Text = "Some text inside Textbox";
MessageBox.Show("TextBox1 Width = " + TextBox1.Width + " & TextBox1.ActualWidth = " + TextBox1.ActualWidth); // NaN & 10
}
}
}
How do I dynamically get the width of TextBox? Width and ActualWidth give me only the default compile time values, but I need the Width property after it has been compiled.
WidthandActualWidthdo not give you the default compile time values.Widthis the requested size.ActualWidthis the rendered size.From MSDN
In your case, if you want the actual size of the item, use
ActualWidth.Edit: Based on your comment, I’m showing you how to make your specific method work, by using a BeginInvoke,to give the ActualWidth a chance to be calculated: