Programowe zmienianie zaznaczenia w RichTextBoxie
W tym przykładzie pokazano, jak programowo zmienić bieżący wybór w RichTextBox. Ten wybór jest taki sam, jak w przypadku wybrania zawartości przez użytkownika przy użyciu interfejsu użytkownika.
Przykład kodu dla kontrolki RichTextBox
Poniższy kod języka XAML (Extensible Application Markup Language) opisuje kontrolkę o nazwie RichTextBox z prostą zawartością.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.ChangeSelectionProgrammaticaly" >
<StackPanel>
<RichTextBox GotMouseCapture="ChangeSelection" Name="richTB">
<FlowDocument>
<Paragraph Name="myParagraph">
<Run>
When the user clicks in the RichTextBox, the selected
text changes programmatically.
</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
</StackPanel>
</Page>
Przykładowy kod do wybierania tekstu z kontrolki RichTextBox
Poniższy kod programowo wybiera dowolny tekst, gdy użytkownik kliknie wewnątrz RichTextBox.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace SDKSample
{
public partial class ChangeSelectionProgrammaticaly : Page
{
// Change the current selection.
void ChangeSelection(Object sender, RoutedEventArgs args)
{
// Create two arbitrary TextPointers to specify the range of content to select.
TextPointer myTextPointer1 = myParagraph.ContentStart.GetPositionAtOffset(20);
TextPointer myTextPointer2 = myParagraph.ContentEnd.GetPositionAtOffset(-10);
// Programmatically change the selection in the RichTextBox.
richTB.Selection.Select(myTextPointer1, myTextPointer2);
}
}
}
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Namespace SDKSample
Partial Public Class ChangeSelectionProgrammaticaly
Inherits Page
' Change the current selection.
Private Sub ChangeSelection(ByVal sender As Object, ByVal args As RoutedEventArgs)
' Create two arbitrary TextPointers to specify the range of content to select.
Dim myTextPointer1 As TextPointer = myParagraph.ContentStart.GetPositionAtOffset(20)
Dim myTextPointer2 As TextPointer = myParagraph.ContentEnd.GetPositionAtOffset(-10)
' Programmatically change the selection in the RichTextBox.
richTB.Selection.Select(myTextPointer1, myTextPointer2)
End Sub
End Class
End Namespace
Zobacz też
Współpracuj z nami w serwisie GitHub
Źródło tej zawartości można znaleźć w witrynie GitHub, gdzie można również tworzyć i przeglądać problemy i żądania ściągnięcia. Więcej informacji znajdziesz w naszym przewodniku dla współtwórców.
.NET Desktop feedback