您可以使用 RichEditBox 控制件來輸入和編輯包含格式化文字、超連結、影像、數學方程式和其他豐富內容的 RTF 檔。 您可以藉由將 IsReadOnly 屬性設成 true,使 RichEditBox 變成唯讀。
這是正確的控制嗎?
使用 RichEditBox 來顯示和編輯文字檔。 您使用 RichEditBox 讓使用者將文字輸入到應用程式的方式,與使用其他標準文字輸入方塊時不一樣。 反之,您會使用它來處理與應用程式分開的文字檔案。 您通常會將輸入至 RichEditBox 的文字儲存至 .rtf 檔案。
- 如果多行文字方塊的主要目的為建立唯讀文件 (例如部落格文章或電子郵件內容),而且這些文件需要 RTF,則改為使用 RTF 方塊。
- 如果要擷取只會消耗且不會向使用者重新顯示的文字,請使用純文字輸入控制項。
- 在所有其他情境中,都請使用純文字輸入控制項。
如需如何選擇正確文字控制項的詳細資訊,請參閱文字控制項文章。
Recommendations
- 建立富文本框時,提供樣式按鈕並執行它們的操作。
- 使用與您的應用程式樣式一致的字型。
- 請確保文字控制項的高度足夠,以容納一般輸入項。
- 不要讓文字輸入控制項的高度隨著使用者輸入增加。
- 使用者只需要單行時,不要使用多行文字方塊。
- 使用純文字控制項就足夠時,不要使用 RTF 控制項。
範例
此 Rich Edit 編輯方塊中有已開啟的 RTF 文件。 格式設定和檔案按鈕並不屬於 Rich Edit 方塊,但您應至少提供一組簡單的樣式設定按鈕並實作它們的動作。
建立 Rich Edit 方塊
WinUI 3 Gallery 應用程式包含大部分 WinUI 3 控制項、特性和功能的互動式範例。 從 Microsoft Store 取得應用程式,或在 GitHub 上取得原始程式碼
根據預設,RichEditBox 可支援拼字檢查。 若要停用拼字檢查程式,請將 IsSpellCheckEnabled 屬性設為 false。 如需詳細資訊,請參閱拼字檢查指導方針一文。
您可以使用 RichEditBox 的 Document 屬性來取得其內容。 RichEditBox 的內容是 ITextDocument 物件,與將 Block 物件當作內容的 RichTextBlock 控制項不同。 ITextDocument 介面可讓您將文件載入和儲存到串流、擷取文字範圍、取得作用中選取項目、復原和重做變更、設定預設格式屬性等。
此範例示範如何在 RichEditBox 中編輯、載入及儲存 RTF (.rtf) 檔案。
<RelativePanel Margin="20" HorizontalAlignment="Stretch">
<RelativePanel.Resources>
<Style TargetType="AppBarButton">
<Setter Property="IsCompact" Value="True"/>
</Style>
</RelativePanel.Resources>
<AppBarButton x:Name="openFileButton" Icon="OpenFile"
Click="OpenButton_Click" ToolTipService.ToolTip="Open file"/>
<AppBarButton Icon="Save" Click="SaveButton_Click"
ToolTipService.ToolTip="Save file"
RelativePanel.RightOf="openFileButton" Margin="8,0,0,0"/>
<AppBarButton Icon="Bold" Click="BoldButton_Click" ToolTipService.ToolTip="Bold"
RelativePanel.LeftOf="italicButton" Margin="0,0,8,0"/>
<AppBarButton x:Name="italicButton" Icon="Italic" Click="ItalicButton_Click"
ToolTipService.ToolTip="Italic" RelativePanel.LeftOf="underlineButton" Margin="0,0,8,0"/>
<AppBarButton x:Name="underlineButton" Icon="Underline" Click="UnderlineButton_Click"
ToolTipService.ToolTip="Underline" RelativePanel.AlignRightWithPanel="True"/>
<RichEditBox x:Name="editor" Height="200" RelativePanel.Below="openFileButton"
RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True"/>
</RelativePanel>
private async void OpenButton_Click(object sender, RoutedEventArgs e)
{
// Open a text file.
Windows.Storage.Pickers.FileOpenPicker open =
new Windows.Storage.Pickers.FileOpenPicker();
open.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
open.FileTypeFilter.Add(".rtf");
Windows.Storage.StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
try
{
Windows.Storage.Streams.IRandomAccessStream randAccStream =
await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// Load the file into the Document property of the RichEditBox.
editor.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
}
catch (Exception)
{
ContentDialog errorDialog = new ContentDialog()
{
Title = "File open error",
Content = "Sorry, I couldn't open the file.",
PrimaryButtonText = "Ok"
};
await errorDialog.ShowAsync();
}
}
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Rich Text", new List<string>() { ".rtf" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until we
// finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
Windows.Storage.Streams.IRandomAccessStream randAccStream =
await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
editor.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);
// Let Windows know that we're finished changing the file so the
// other app can update the remote version of the file.
Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
{
Windows.UI.Popups.MessageDialog errorBox =
new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
await errorBox.ShowAsync();
}
}
}
private void BoldButton_Click(object sender, RoutedEventArgs e)
{
Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
if (selectedText != null)
{
Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
charFormatting.Bold = Windows.UI.Text.FormatEffect.Toggle;
selectedText.CharacterFormat = charFormatting;
}
}
private void ItalicButton_Click(object sender, RoutedEventArgs e)
{
Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
if (selectedText != null)
{
Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
charFormatting.Italic = Windows.UI.Text.FormatEffect.Toggle;
selectedText.CharacterFormat = charFormatting;
}
}
private void UnderlineButton_Click(object sender, RoutedEventArgs e)
{
Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection;
if (selectedText != null)
{
Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
if (charFormatting.Underline == Windows.UI.Text.UnderlineType.None)
{
charFormatting.Underline = Windows.UI.Text.UnderlineType.Single;
}
else {
charFormatting.Underline = Windows.UI.Text.UnderlineType.None;
}
selectedText.CharacterFormat = charFormatting;
}
}
使用富文本編輯框來編輯數學公式
RichEditBox 可以使用 UnicodeMath 來顯示和編輯數學方程式。 方程式會以 MathML 3.0 格式儲存和擷取。
根據預設,RichEditBox 控件不會將輸入解譯為數學。 若要啟用數學模式,請在 TextDocument 屬性上呼叫 SetMathMode,傳遞 RichEditMathMode.MathOnly 值(若要停用數學模式,請呼叫 SetMathMode,但傳入值 NoMath)。
richEditBox.TextDocument.SetMathMode(Microsoft.UI.Text.RichEditMathMode.MathOnly);
這可讓 UnicodeMath 輸入即時自動辨識並轉換成 MathML。 例如,輸入 4^2 會轉換成 42,而 1/2 會轉換成 1/2。 如需更多範例,請參閱 WinUI 3 資源庫應用程式 。
若要將豐富編輯框的數學內容儲存為MathML字串,請呼叫 GetMathML。
richEditBox.TextDocument.GetMathML(out String mathML);
若要設定豐富編輯框的數學內容,請呼叫 SetMathML,傳入 MathML 字串。
選擇適合文字控制的鍵盤
若要協助使用者使用觸控式鍵盤或軟體輸入面板 (SIP) 輸入數據,您可以設定文字控制件的輸入範圍,以符合使用者預期輸入的數據種類。 預設鍵盤配置通常適合操作 RTF 文件。
如需詳細瞭解如何使用輸入範圍,請參閱使用輸入範圍來變更觸控式鍵盤。
UWP 和 WinUI 2
這很重要
本文中的資訊和範例針對使用 Windows App SDK 和 WinUI 3 的應用程式進行了最佳化,但通常適用於使用 WinUI 2 的 UWP 應用程式。 如需平台特定資訊和範例,請參閱 UWP API 參考。
本節包含您在 UWP 或 WinUI 2 應用程式中使用控制項所需的資訊。
此控制項的 API 位在 Windows.UI.Xaml.Controls 命名空間中。
- UWP API:RichEditBox 類別、Document 屬性、IsReadOnly 屬性、IsSpellCheckEnabled 屬性
- 開啟 WinUI 2 程式庫應用程式,並查看 RichEditBox 運作情形。 WinUI 2 圖庫應用程式包含了大部分 WinUI 2 控制項、特性和功能的互動式範例。 從 Microsoft Store 取得應用程式,或在 GitHub 上取得原始程式碼。
建議使用最新的 WinUI 2 來取得所有控制項的最新樣式和範本。 WinUI 2.2 或更新版本包含一個供此控制項使用的新範本,其採用了圓角設計。 如需詳細資訊,請參閱圓角半徑。