12

Possible Duplicate:
Any way to make a WPF textblock selectable?

Can I make a textblock selectable in WPF application so that a user can copy it.

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
D J
  • 6,638
  • 13
  • 40
  • 74
  • Ah damn, Jay Riggs is right... I should have considered before re-iterating. +1 – Chris W. Oct 04 '12 at 04:17
  • The question can't be answered by erroneous answer with over 20 up-vote from provided link. I voted this question to reopen. It is no sense that it more one year old. – Hamlet Hakobyan Mar 04 '14 at 00:38
  • I found a better solution. Please check my answer here: https://stackoverflow.com/a/45627524/332528 – torvin Aug 11 '17 at 05:24

1 Answers1

13

You could just make it into a TextBox that's Read Only which just looks like a TextBlock, kind of like;

<Style x:Key="ReadOnlyTextBox" TargetType="TextBox">
   <Setter Property="IsReadOnly" Value="True" />
   <Setter Property="Padding" Value="5"/>
   <Setter Property="Margin" Value="0"/>
   <Setter Property="Background" Value="Transparent"/>
   <Setter Property="BorderBrush" Value="Transparent"/>
   <Setter Property="BorderThickness" Value="0"/>
   <Setter Property="IsTabStop" Value="False"/>
   <Setter Property="HorizontalScrollBarVisibility" Value="Disabled"/>
   <Setter Property="VerticalScrollBarVisibility" Value="Disabled"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="TextBox">
            <Grid x:Name="RootElement">
               <ScrollViewer x:Name="ContentElement"
                             Margin="{TemplateBinding Margin}"
                             Background="{TemplateBinding Background}"
                             BorderBrush="{TemplateBinding BorderBrush}"
                             BorderThickness="{TemplateBinding BorderThickness}"
                             IsTabStop="{TemplateBinding IsTabStop}"
                             Padding="{TemplateBinding Padding}" 
                             HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
                             VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"/>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

The ScrollViewer ContentElement would be in a TextBox by default, you could substitute for a ContentPresenter instead if you like also.

Then put it into effect;

<TextBox Text="Blah Blah Blah you can copy me!" Style="{StaticResource ReadOnlyTextBox}"/>

Hope this helps!

ADDENDUM: As @doodleus pointed out in the comments. Template binding the Content Property within the template may be necessary. As "ContentElement" is a named part of the Silverlight TextBox control. One of the little nuance differences to watch for in the different xaml Variants. I must not have paid attention to the Tags when I originally created the example. So kudos to him for correcting me.

Chris W.
  • 21,954
  • 3
  • 54
  • 92