In XAML how to say: default width and height for e.g. TextBox

Edward Tanguay picture Edward Tanguay · Feb 2, 2009 · Viewed 26.7k times · Source

So I'm coming at WPF from a HTML perspective.

I just want to put a TextBox on my Window like this:

<Grid>
    <TextBox Name="theName" />
</Grid>

Turns out that the TextBox is then HUGE, covers the whole window. (!)

Ok, that's not what I want, but I don't want to define the EXACT size either since I know Height and Width should be flexible, so I try:

<TextBox Name="theName" Width="Auto" Height="Auto"/>

Same thing. So I try:

<TextBox Name="theName" 
    HorizontalAlignment="Stretch" 
    VerticalAlignment="Stretch"/>

Same thing. So I just hard code the sizes:

<TextBox Name="theName" Width="100" Height="20"/>

Which I know is not a good programming practice in WPF.

So, what how do you tell TextBox to "display default sizes for the font size being used"?

Answer

Steve Brouillard picture Steve Brouillard · Feb 2, 2009

You can take Bryan's example even a bit further. By specifying a specific alignment that isn't stretch and further constrain the TextBox so that it won't expand beyond a certain size. eg:

<Grid x:Name="LayoutRoot">
        <TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Text="TextBox" TextWrapping="Wrap" 
        MinWidth="15" MinHeight="20" MaxWidth="500" MaxHeight="50"/>
</Grid>

You can take it even further by setting up rows/columns inside the Grid and constraining them in various fashions. As you're coming from an HTML background, think of it like using a table to control layout. Remember that you can also nest other container objects (i.e. StackPanels, WrapPanels, other Grids, etc...).

The challenge with XAML and the WPF/Silverlight controls is that they a very flexible, so you've got to get a handle on all the options and how they affect layout.

Good luck. I'm going through this exact same thing now.