Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Windows Phone 7 TextBox style margin issue

0.00/5 (No votes)
19 Mar 2013 1  
Avoid unwanted margin in disabled TextBox.

Introduction

I found a strange behavior of TextBox. When it's in disabled state and it has a non-zero margin, the inner text looks shifted:

To reproduce it, just create a new Silverlight WP app and add the following code to a grid named ContentPanel:

<StackPanel Margin="0,12,0,0">
	<StackPanel.Resources>
		<Style TargetType="TextBlock">
			<Setter Property="Margin" Value="25,0,25,0"/>
		</Style>
		<Style TargetType="TextBox">
			<Setter Property="Margin" Value="33,0,13,0"/>
		</Style>
	</StackPanel.Resources>

	<TextBlock Text="Name:" />
	<TextBox Text="some test text" IsEnabled="False" />

	<TextBlock Text="E-mail:"/>
	<TextBox Text="test@movaxbx.com" InputScope="EmailNameOrAddress" />
</StackPanel>

The reason is that in the default control template disabled state is described using TextBox. Here is a short version of the default control template (you can get a full version with Expression Blend):  

...
<Border x:Name="EnabledBorder" ... > 
    <ContentControl x:Name="ContentElement" .../> 
</Border> 
<Border x:Name="DisabledOrReadonlyBorder" ... > 
    <TextBox .../> 
</Border>
...

In the case of setting IsEnabled="False", EnabledBorder is hidden and DisabledOrReadonlyBorder is visible. So the textbox is rendered using TextBox.  

You will notice in the first code sample the style for TextBox without x:Key. It means, that style applied to any of the child TextBox. So the margin from style's setter is applied to the control template’s inner TextBox too. And that’s the reason why we have a shifted text in the disabled state!  

As a solution 

You can add x:Key for TextBox style and apply it manually to every TextBox. In this case the disabled state will work normally.

The same is valid for PasswordBox too. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here