Click here to Skip to main content
15,883,705 members
Articles / Mobile Apps / Windows Phone 7
Tip/Trick

Windows Phone 7 TextBox style margin issue

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Mar 2013CPOL 12K   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:

Image 1

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

HTML
<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):  

HTML
...
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --