Reputation: 709
When setting the Text property of a WPF TextBox control, other properties that should also change (as a side effect) do not change. In particular, I would like to check the value of the ExtentWidth property after setting Text, but it does not change. I've tried calling UpdateLayout() to no avail. In Windows.Forms, I would call DoEvents().
OK, here's some code. I put this in the Window_Loaded() event handler. The problem is that textBox.ExtentWidth doesn't change when textBox.Text changes. That doesn't really surprise me. I figure I need to call something like textBox.UpdateLayout() to make it recalculate ExtentWidth, but that didn't help. ExtentWidth does vary depending on what I initialize textBox.Text to in the Window's constructor, but that doesn't help me. I need to set several different Text values and get the corresponding ExtentWidth for each.
string initText = textBox.Text; // "textBox"
double extentWidth = textBox.ExtentWidth; // 39.3
textBox.Text = "short text";
extentWidth = textBox.ExtentWidth; // 39.3
textBox.Text = "Long enough to make a difference, eh?";
extentWidth = textBox.ExtentWidth; // 39.3
Upvotes: 1
Views: 1067
Reputation: 709
I found a solution to the specific problem of getting TextBox.ExtentWidth
to change after setting Text. Setting Text will raise the LayoutUpdated
event, and you can get the new value of ExtentWidth
in a handler for LayoutUpdated
.
I used this fact to create a subclass of WPF TextBox
that displays an ellipsis when the text is too long for the visible area. I wrote a CodeProject article about it here.
Upvotes: 1