Copyable TextBlock for Windows Phone

The latest update for Windows Phone 7 adds automatic support for Copy and Paste to TextBox controls in your application. By default this means you can’t copy text from static TexBlock controls. There is however a solution which requires minimal changes to implement. You have to replace the TextBlock control with a TextBox and set the IsReadOnly property to true. At first glance this will totally ruin the look of your application – even if you set custom background/foreground colours the control will display in grey on grey when IsReadOnly is true. It is possible to change this behaviour by applying a custom template to the control. Originally I did this in Blend but I found it had generated much more XAML than absolutely necessary so I set about removing redundant parts to result in this:-

<ControlTemplate x:Key="PhoneDisabledTextBoxTemplate" TargetType="TextBox">
            <ContentControl x:Name="ContentElement" BorderThickness="0" HorizontalContentAlignment="Stretch" Margin="{StaticResource PhoneTextBoxInnerMargin}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="Stretch"/>

Simply add this to the Resources collection for your page.

Then your TextBox is customised like so:-

<TextBox Grid.Row="1" Name="TextBlockCopyable" IsReadOnly="True" TextWrapping="Wrap" Foreground="{StaticResource PhoneForegroundBrush}" Template="{StaticResource PhoneDisabledTextBoxTemplate}" Text="We provide software solutions for a mobile world. We have unrivalled expertise in designing, developing and supporting mobile software for Windows Phone and Windows Embedded." FontSize="{StaticResource PhoneFontSizeMedium}" />

The result looks and behaves like a TextBlock and still follows your system theme but allows copying on the latest emulator:-


I created a sample project with all of the code showing the different behaviours of the TextBlock, read-only TextBox and customised TextBox which you can download here:- (44kb)

By Peter Foot

Microsoft Windows Development MVP