简体   繁体   中英

How do i get the Width of TextBox at runtime?

<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.

Width and ActualWidth do not give you the default compile time values.

Width is the requested size.

ActualWidth is the rendered size. From MSDN

ActualWidth is a calculated value, and there can be multiple or incremental reported changes to the value because of operations by the layout system. If you get the value while layout is still iterating, the layout system might still be calculating the required measure of space for child objects, constraints by the parent object, and so on.

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:

private void TextBox1_PreviewKeyUp_1(object sender, KeyEventArgs e)
{
        TextBox1.Text = "Some other text";
        Dispatcher.BeginInvoke((Action)new Action(() =>
            MessageBox.Show("TextBox1 Width = " + TextBox1.Width + " & TextBox1.ActualWidth = " + TextBox1.ActualWidth)),
          System.Windows.Threading.DispatcherPriority.Input);
}

Use JavaScript as it's the only way to get the correct size of the Textarea on the Client side as they could be using any browser? If you have jQuery very easy to do can also be done with native javascript.

Then get JavaScript to post that value in a Hidden input and get the value of the Input in your server based code to use where needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM