daewoosh
daewoosh

Reputation: 323

Text selection on textblock and label wpf

I have a form, which includes TextBlocks, Lables, Borders. And I want to be able to select text with the mouse like it would be some text in the table in MS Word or HTML table. And I can't use TextBox or RichTextBox instead. Is there a way to achive my goal?

<Grid Margin="20">
<Grid.RowDefinitions>
    <RowDefinition Height="auto"/>
    <RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="1">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="some text in TextBlock" VerticalAlignment="Center"/>
        <Label Content="another text in Label"/>
    </StackPanel>
</Border>
<Border Grid.Row="1" BorderBrush="Black" BorderThickness="1">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="one more  in TextBlock" VerticalAlignment="Center"/>
        <Label Content="one more text in Label"/>
    </StackPanel>
</Border>

Upvotes: 3

Views: 8361

Answers (2)

Mohammed A. Fadil
Mohammed A. Fadil

Reputation: 9377

Use TextBox instead of a TextBlock, like the following code:

<TextBox
     Background="Transparent"
     TextWrapping="Wrap"
     Text="{Binding Desired, Mode=OneWay}"
     IsReadOnly="True"
     BorderThickness="0"/>

To make it cleaner, careate a template for the TextBlock and use the previous TextBox inside it.

Upvotes: 3

David Škarda
David Škarda

Reputation: 40

You can achieve it like this:

<TextBlock Text="test2"
           FontSize="16"
           IsTextSelectionEnabled="true"
           SelectionHighlightColor="Green"
           x:Name="test"      
           Foreground="Black"
           TextWrapping="Wrap"
           TextAlignment="Left"/>

Just set IsTextSelectionEnabled to true. You can also chagne color of selected text by changing SelectionHighlightColor property.

Upvotes: -2

Related Questions