Selection Property

RichTextBox.Selection Property

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Gets the TextSelection in the RichTextBox.

Namespace:  System.Windows.Controls
Assembly:  System.Windows (in System.Windows.dll)

'Declaration
Public ReadOnly Property Selection As TextSelection

Property Value

Type: System.Windows.Documents.TextSelection
A TextSelection that represents the selected text in the RichTextBox.

The following example shows how you can apply bold, italic, and underline formatting to the selected text.


<!--Create a RichTextBox and three buttons.-->
<StackPanel>
    <RichTextBox x:Name="MyRTB" Width="600" Height="400" />
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Button Content="Bold" Height="30" Margin="2" Width="50" Click="BtnBold_Click" />
        <Button Content="Italic" Height="30" Margin="2" Width="50" Click="BtnItalic_Click" />
        <Button Content="Underline" Height="30" Margin="2" Width="65" Click="BtnUnderline_Click" />
    </StackPanel>
</StackPanel>



'Set Bold formatting to selected content
Private Sub BtnBold_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If MyRTB IsNot Nothing Then
        If TypeOf MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty) Is FontWeight _
            AndAlso (CType(MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty), FontWeight) = FontWeights.Normal) Then
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal)
        End If
    End If
End Sub


'Set Italic formatting to selected content
Private Sub BtnItalic_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If MyRTB IsNot Nothing Then
        If TypeOf MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty) Is FontStyle _
            AndAlso (CType(MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty), FontStyle) = FontStyles.Normal) Then
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Italic)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Normal)
        End If
    End If
End Sub


'Set Underline formatting to selected content
Private Sub BtnUnderline_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If (Not (MyRTB) Is Nothing) Then
        If (MyRTB.Selection.GetPropertyValue(Run.TextDecorationsProperty) Is Nothing) Then
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, Nothing)
        End If
    End If
End Sub


Windows Phone OS

Supported in: 8.1, 8.0, 7.1

Windows Phone

Show:
© 2017 Microsoft