Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

RichTextBox.Selection Property

Gets the TextSelection in the RichTextBox.

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

public TextSelection Selection { get; }

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.

Run this sample


<!--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 void BtnBold_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty) is FontWeight && ((FontWeight)MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty)) == FontWeights.Normal)
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal);

    }

}
//<SnippetItalic>
//Set Italic formatting to selected content
private void BtnItalic_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty) is FontStyle && ((FontStyle)MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty)) == FontStyles.Normal)
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Italic);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Normal);
    }


}

//Set Underline formatting to selected content
private void BtnUnderline_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.TextDecorationsProperty) == null)
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, null);
    }

}


Silverlight

Supported in: 5, 4

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft