65.9K
CodeProject is changing. Read more.
Home

Windows Phone 7 TextBox style margin issue

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Dec 25, 2012

CPOL
viewsIcon

12184

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.