Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - How to stop TextBox from autosizing?

I have a textbox in my visual tree as follows..

  • Window
    • Grid
      • ListBox
        • ItemTemplate
          • DataTemplate
            • Grid
              • Grid
                • Textbox...
The textbox is defined as..
<TextBox Height="Auto" 
         Text="{Binding Path=LyricsForDisplay}" 
         MinHeight="50" 
         MaxHeight="400"  
         Visibility="Visible" 
         VerticalScrollBarVisibility="Auto" 
         IsReadOnly="True" 
         AllowDrop="False" 
         TextWrapping="WrapWithOverflow">
</TextBox>

When long text is added to the bound variable (LyricsForDisplay) all of the items in the listbox expand their textboxes/grids width's to allow for the entire string to be seen if you use the scrollbar on bottom that appears...

What I would like to do is make it so the boxes/grids only resize if the user stretches the window .. NOT when a long text is entered (it could just wrap around..)

Does anyone know how to obtain the functionality?

like image 951
Ryan Avatar asked Dec 16 '10 21:12

Ryan


1 Answers

Unfortunately, the regular TextBox doesn't allow autoresize to fit the parent but NOT autoresize when the text doesn't fit.

To solve this problem, you can use a custom TextBox that reports a desired (0, 0) size. It's an ugly hack, but it works.

In your .xaml.cs file:

public class TextBoxThatDoesntResizeWithText : TextBox
{
    protected override Size MeasureOverride(Size constraint)
    {
        return new Size(0, 0);
    }
}

Then, in your .xaml file:

<Window x:Class="YourNamespace.YourWindow"
    ...
    xmlns:local="clr-namespace:YourNamespace">
        ...
        <local:TextBoxThatDoesntResizeWithText Height="Auto" 
                                               Text="{Binding Path=LyricsForDisplay}" 
                                               MinHeight="50" 
                                               MaxHeight="400"  
                                               Visibility="Visible" 
                                               VerticalScrollBarVisibility="Auto" 
                                               IsReadOnly="True" 
                                               AllowDrop="False" 
                                               TextWrapping="WrapWithOverflow">
        </local:TextBoxThatDoesntResizeWithText>
        ...
</Window>
like image 97
ajarov Avatar answered Oct 02 '22 13:10

ajarov