Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Элемент RichTextBox управления позволяет отображать или изменять содержимое потока, включая абзацы, изображения, таблицы и многое другое. В этом разделе представлен класс TextBox и приведены примеры использования в языке разметки расширяемых приложений (XAML) и C#.
TextBox или RichTextBox?
И RichTextBox, и TextBox позволяют пользователям изменять текст, однако эти элементы управления используются в разных сценариях. Лучше выбрать RichTextBox, когда пользователю необходимо изменить форматированный текст, изображения, таблицы или другое содержимое с форматированием. Например, редактирование документа, статьи или блога, требующего форматирования, изображений и т. д., лучше всего выполнять с помощью RichTextBox. Для TextBox требуется меньше системных ресурсов, чем RichTextBox, и это идеальный выбор, когда нужно редактировать только простой текст (т. е. используется в формах). Дополнительные сведения см. в разделе "Обзор TextBox" по TextBox. В таблице ниже приведены основные функции TextBox и RichTextBox.
Контроль | Проверка орфографии в режиме реального времени | Контекстное меню | Команды форматирования, такие как ToggleBold (Ctr+B) | FlowDocument содержимое, такое как изображения, абзацы, таблицы и т. д. |
---|---|---|---|---|
TextBox | Да | Да | нет | Нет. |
RichTextBox | Да | Да | Да | Да |
Замечание
Хотя TextBox не поддерживает форматирование связанных команд, таких как ToggleBold (Ctr+B), многие основные команды поддерживаются обеими элементами управления, такими как MoveToLineEnd.
Более подробно описаны функции из приведенной выше таблицы.
Создание RichTextBox
В приведенном ниже коде показано, как создать объект RichTextBox, в котором пользователь может изменять богатое содержимое.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- A RichTextBox with no initial content in it. -->
<RichTextBox />
</Page>
В частности, редактируемое содержимое в RichTextBox является потоком данных. Содержимое потока может содержать множество типов элементов, включая форматированный текст, изображения, списки и таблицы. Подробные сведения о документах потока см. в разделе "Общие сведения о документах потока ". Чтобы удерживать содержимое потока, RichTextBox размещает объект FlowDocument, который, в свою очередь, содержит редактируемое содержимое. Для демонстрации содержимого потока в RichTextBox, в следующем коде показано, как создать RichTextBox, содержащий абзац и полужирный текст.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<RichTextBox>
<FlowDocument>
<Paragraph>
This is flow content and you can <Bold>edit me!</Bold>
</Paragraph>
</FlowDocument>
</RichTextBox>
</StackPanel>
</Page>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Documents;
namespace SDKSample
{
public partial class BasicRichTextBoxWithContentExample : Page
{
public BasicRichTextBoxWithContentExample()
{
StackPanel myStackPanel = new StackPanel();
// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();
// Create a Run of plain text and some bold text.
Run myRun = new Run("This is flow content and you can ");
Bold myBold = new Bold(new Run("edit me!"));
// Create a paragraph and add the Run and Bold to it.
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(myRun);
myParagraph.Inlines.Add(myBold);
// Add the paragraph to the FlowDocument.
myFlowDoc.Blocks.Add(myParagraph);
RichTextBox myRichTextBox = new RichTextBox();
// Add initial content to the RichTextBox.
myRichTextBox.Document = myFlowDoc;
myStackPanel.Children.Add(myRichTextBox);
this.Content = myStackPanel;
}
}
}
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Documents
Namespace SDKSample
Partial Public Class BasicRichTextBoxWithContentExample
Inherits Page
Public Sub New()
Dim myStackPanel As New StackPanel()
' Create a FlowDocument to contain content for the RichTextBox.
Dim myFlowDoc As New FlowDocument()
' Create a Run of plain text and some bold text.
Dim myRun As New Run("This is flow content and you can ")
Dim myBold As New Bold(New Run("edit me!"))
' Create a paragraph and add the Run and Bold to it.
Dim myParagraph As New Paragraph()
myParagraph.Inlines.Add(myRun)
myParagraph.Inlines.Add(myBold)
' Add the paragraph to the FlowDocument.
myFlowDoc.Blocks.Add(myParagraph)
Dim myRichTextBox As New RichTextBox()
' Add initial content to the RichTextBox.
myRichTextBox.Document = myFlowDoc
myStackPanel.Children.Add(myRichTextBox)
Me.Content = myStackPanel
End Sub
End Class
End Namespace
На следующем рисунке показано, как отрисовывается этот пример.
Такие элементы, как Paragraph и Bold, определяют то, как содержимое внутри RichTextBox отображается. Когда пользователь редактирует RichTextBox содержимое, он изменяет контент потока. Дополнительные сведения о содержимом потока и работе с ним см. в разделе Общие сведения о документе потока.
Замечание
Содержимое потока внутри RichTextBox ведёт себя не так, как содержимое потока, находящееся в других элементах управления. Например, в RichTextBox нет столбцов и, поэтому, нет поведения автоматического изменения размера. Кроме того, встроенные функции, такие как поиск, режим просмотра, навигация по страницам и масштабирование, недоступны в пределах RichTextBox.
Проверка орфографии в режиме реального времени
Вы можете включить проверку орфографии в режиме реального времени в TextBox или RichTextBox. При включении проверки орфографии красная линия отображается под любыми прописными словами (см. рисунок ниже).
См. включение проверки орфографии в элементе управления редактирования текста, чтобы узнать, как включить проверку орфографии.
Контекстное меню
По умолчанию оба TextBox и RichTextBox имеют контекстное меню, которое отображается при щелчке правой кнопкой мыши пользователя внутри элемента управления. Контекстное меню позволяет пользователю вырезать, копировать или вставлять (см. рисунок ниже).
Вы можете создать собственное пользовательское контекстное меню, чтобы переопределить его по умолчанию. Дополнительные сведения см. в разделе "Положение настраиваемого контекстного меню" в RichTextBox .
Редактирование команд
Команды редактирования позволяют пользователям форматировать редактируемое содержимое внутри RichTextBox. Помимо основных команд редактирования, RichTextBox включает команды форматирования, которые TextBox не поддерживает. Например, при редактировании в RichTextBox пользователь может нажать клавишу Ctrl+B, чтобы включить или отключить жирный текст. См. EditingCommands для полного списка доступных команд. Помимо сочетаний клавиш, можно подключить команды к другим элементам управления, таким как кнопки. В следующем примере показано, как создать простую панель инструментов, содержащую кнопки, которые пользователь может использовать для изменения форматирования текста.
<Window x:Class="RichTextBoxInputPanelDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="400" Width="600"
>
<Grid>
<!-- Set the styles for the tool bar. -->
<Grid.Resources>
<Style TargetType="{x:Type Button}" x:Key="formatTextStyle">
<Setter Property="FontFamily" Value="Palatino Linotype"></Setter>
<Setter Property="Width" Value="30"></Setter>
<Setter Property="FontSize" Value ="14"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
</Style>
<Style TargetType="{x:Type Button}" x:Key="formatImageStyle">
<Setter Property="Width" Value="30"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
</Style>
</Grid.Resources>
<DockPanel Name="mainPanel">
<!-- This tool bar contains all the editing buttons. -->
<ToolBar Name="mainToolBar" Height="30" DockPanel.Dock="Top">
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Cut" ToolTip="Cut">
<Image Source="Images\EditCut.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Copy" ToolTip="Copy">
<Image Source="Images\EditCopy.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Paste" ToolTip="Paste">
<Image Source="Images\EditPaste.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Undo" ToolTip="Undo">
<Image Source="Images\EditUndo.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Redo" ToolTip="Redo">
<Image Source="Images\EditRedo.png"></Image>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleBold" ToolTip="Bold">
<TextBlock FontWeight="Bold">B</TextBlock>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleItalic" ToolTip="Italic">
<TextBlock FontStyle="Italic" FontWeight="Bold">I</TextBlock>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleUnderline" ToolTip="Underline">
<TextBlock TextDecorations="Underline" FontWeight="Bold">U</TextBlock>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseFontSize" ToolTip="Grow Font">
<Image Source="Images\CharacterGrowFont.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseFontSize" ToolTip="Shrink Font">
<Image Source="Images\CharacterShrinkFont.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleBullets" ToolTip="Bullets">
<Image Source="Images\ListBullets.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleNumbering" ToolTip="Numbering">
<Image Source="Images/ListNumbering.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignLeft" ToolTip="Align Left">
<Image Source="Images\ParagraphLeftJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignCenter" ToolTip="Align Center">
<Image Source="Images\ParagraphCenterJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignRight" ToolTip="Align Right">
<Image Source="Images\ParagraphRightJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignJustify" ToolTip="Align Justify">
<Image Source="Images\ParagraphFullJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseIndentation" ToolTip="Increase Indent">
<Image Source="Images\ParagraphIncreaseIndentation.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseIndentation" ToolTip="Decrease Indent">
<Image Source="Images\ParagraphDecreaseIndentation.png"></Image>
</Button>
</ToolBar>
<!-- By default pressing tab moves focus to the next control. Setting AcceptsTab to true allows the
RichTextBox to accept tab characters. -->
<RichTextBox Name="mainRTB" AcceptsTab="True"></RichTextBox>
</DockPanel>
</Grid>
</Window>
На следующем рисунке показано, как отображается этот пример.
Обнаружение изменений содержимого
Как правило, событие TextChanged должно использоваться для обнаружения случаев, когда текст в TextBox или RichTextBox изменяется, вместо KeyDown, как можно было бы ожидать. Пример см. в статье Обнаружение изменений текста в текстовом поле.
Сохранение, загрузка и печать содержимого RichTextBox
В следующем примере показано, как сохранить содержимое RichTextBox в файл, загрузить его обратно в RichTextBoxи распечатать содержимое. Ниже приведена разметка для примера.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.SaveLoadPrintRTB" >
<StackPanel>
<RichTextBox Name="richTB">
<FlowDocument>
<Paragraph>
<Run>Paragraph 1</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Click="SaveRTBContent">Save RTB Content</Button>
<Button Click="LoadRTBContent">Load RTB Content</Button>
<Button Click="PrintRTBContent">Print RTB Content</Button>
</StackPanel>
</Page>
Ниже приведен код для примера.
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace SDKSample
{
public partial class SaveLoadPrintRTB : Page
{
// Handle "Save RichTextBox Content" button click.
void SaveRTBContent(Object sender, RoutedEventArgs args)
{
// Send an arbitrary URL and file name string specifying
// the location to save the XAML in.
SaveXamlPackage("C:\\test.xaml");
}
// Handle "Load RichTextBox Content" button click.
void LoadRTBContent(Object sender, RoutedEventArgs args)
{
// Send URL string specifying what file to retrieve XAML
// from to load into the RichTextBox.
LoadXamlPackage("C:\\test.xaml");
}
// Handle "Print RichTextBox Content" button click.
void PrintRTBContent(Object sender, RoutedEventArgs args)
{
PrintCommand();
}
// Save XAML in RichTextBox to a file specified by _fileName
void SaveXamlPackage(string _fileName)
{
TextRange range;
FileStream fStream;
range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.Create);
range.Save(fStream, DataFormats.XamlPackage);
fStream.Close();
}
// Load XAML into RichTextBox from a file specified by _fileName
void LoadXamlPackage(string _fileName)
{
TextRange range;
FileStream fStream;
if (File.Exists(_fileName))
{
range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.XamlPackage);
fStream.Close();
}
}
// Print RichTextBox content
private void PrintCommand()
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
//use either one of the below
pd.PrintVisual(richTB as Visual, "printing as visual");
pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
}
}
}
}
Imports System.IO
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Media
Namespace SDKSample
Partial Public Class SaveLoadPrintRTB
Inherits Page
' Handle "Save RichTextBox Content" button click.
Private Sub SaveRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)
' Send an arbitrary URL and file name string specifying
' the location to save the XAML in.
SaveXamlPackage("C:\test.xaml")
End Sub
' Handle "Load RichTextBox Content" button click.
Private Sub LoadRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)
' Send URL string specifying what file to retrieve XAML
' from to load into the RichTextBox.
LoadXamlPackage("C:\test.xaml")
End Sub
' Handle "Print RichTextBox Content" button click.
Private Sub PrintRTBContent(ByVal sender As Object, ByVal args As RoutedEventArgs)
PrintCommand()
End Sub
' Save XAML in RichTextBox to a file specified by _fileName
Private Sub SaveXamlPackage(ByVal _fileName As String)
Dim range As TextRange
Dim fStream As FileStream
range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
fStream = New FileStream(_fileName, FileMode.Create)
range.Save(fStream, DataFormats.XamlPackage)
fStream.Close()
End Sub
' Load XAML into RichTextBox from a file specified by _fileName
Private Sub LoadXamlPackage(ByVal _fileName As String)
Dim range As TextRange
Dim fStream As FileStream
If File.Exists(_fileName) Then
range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
fStream = New FileStream(_fileName, FileMode.OpenOrCreate)
range.Load(fStream, DataFormats.XamlPackage)
fStream.Close()
End If
End Sub
' Print RichTextBox content
Private Sub PrintCommand()
Dim pd As New PrintDialog()
If (pd.ShowDialog() = True) Then
'use either one of the below
pd.PrintVisual(TryCast(richTB, Visual), "printing as visual")
pd.PrintDocument(((CType(richTB.Document, IDocumentPaginatorSource)).DocumentPaginator), "printing as paginator")
End If
End Sub
End Class
End Namespace
См. также
.NET Desktop feedback