次の方法で共有


リッチ エディット ボックス

RichEditBox コントロールを使用すると、書式設定されたテキスト、ハイパーリンク、画像、数式、その他のリッチ コンテンツを含むリッチ テキスト ドキュメントを入力および編集できます。 RichEditBox を読み取り専用にするには、その IsReadOnly プロパティを true に設定 します

これは適切なコントロールですか?

RichEditBox を使用して、テキスト ファイルを表示および編集します。 RichEditBox を使用して、他の標準テキスト入力ボックスを使用する方法でユーザー入力をアプリに取り込むことはありません。 代わりに、アプリとは別のテキスト ファイルを操作するために使用します。 通常、RichEditBox に入力されたテキストを.rtf ファイルに保存します。

  • 複数行テキスト ボックスの主な目的が、読み取り専用ドキュメント (ブログ エントリや電子メール メッセージの内容など) を作成することであり、それらのドキュメントにリッチ テキストが必要な場合は、代わりに リッチ テキスト ブロック を使用します。
  • 使用され、ユーザーに再表示されないテキストをキャプチャする場合は、プレーン テキスト入力コントロールを使用します。
  • その他のすべてのシナリオでは、プレーン テキスト入力コントロールを使用します。

適切なテキスト コントロールの選択の詳細については、「 テキスト コントロール 」の記事を参照してください。

推奨事項

  • リッチ テキスト ボックスを作成する場合は、スタイル設定ボタンを用意し、その動作を実装します。
  • アプリのスタイルに合ったフォントを使用します。
  • テキスト コントロールの高さは、典型的な入力が十分に入るように設定します。
  • ユーザーの入力中にテキスト入力コントロールの高さが増加するようにはしません。
  • ユーザーが 1 行しか必要としていない場合は、複数行テキスト ボックスを使用しません。
  • プレーンテキスト コントロールで十分な場合に、リッチ テキスト コントロールを使用しません。

このリッチ エディット ボックスには、リッチ テキスト ドキュメントが開いています。 書式設定ボタンとファイル ボタンは、リッチ エディット ボックスの一部ではありませんが、少なくとも最小限のスタイル設定ボタンのセットを指定し、それらのアクションを実装する必要があります。

ドキュメントを開いたリッチ テキスト ボックス

リッチ エディット ボックスを作成する

WinUI 3 ギャラリー アプリには、ほとんどの WinUI 3 コントロール、機能、および機能の対話型の例が含まれています。 Microsoft Store からアプリを取得するか、GitHub でソース コードを取得する

既定では、RichEditBox はスペル チェックをサポートしています。 スペル チェックを無効にするには、 IsSpellCheckEnabled プロパティを false に設定 します。 詳細については、 スペル チェックのガイドライン に関する記事を参照してください。

RichEditBox の Document プロパティを使用して、そのコンテンツを取得します。 RichEditBox のコンテンツは、コンテンツとして Block オブジェクトを使用する RichTextBlock コントロールとは異なり、ITextDocument オブジェクトです。 ITextDocument インターフェイスを使用すると、ドキュメントをストリームに読み込んで保存したり、テキスト範囲を取得したり、アクティブな選択範囲を取得したり、変更を元に戻したりやり直したり、既定の書式設定属性を設定したりできます。

この例では、リッチ テキスト形式 (.rtf) ファイルを RichEditBox に編集、読み込み、保存する方法を示します。

<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) でデータを入力できるように、ユーザーが入力すると予想されるデータの種類に合わせてテキスト コントロールの入力値の種類を設定できます。 通常、既定のキーボード レイアウトはリッチ テキスト ドキュメントの操作に適しています。

入力スコープの使用方法の詳細については、「入力スコープを 使用してタッチ キーボードを変更する」を参照してください。

UWP と WinUI 2

重要

この記事の情報と例は、 Windows App SDKWinUI 3 を使用するアプリ向けに最適化されていますが、一般的には WinUI 2 を使用する UWP アプリに適用されます。 プラットフォーム固有の情報と例については、UWP API リファレンスを参照してください。

このセクションには、UWP または WinUI 2 アプリでコントロールを使用するために必要な情報が含まれています。

このコントロールの API は 、Windows.UI.Xaml.Controls 名前空間に存在します。

最新の WinUI 2 を使用して、すべてのコントロールの最新のスタイルとテンプレートを取得することをお勧めします。 WinUI 2.2 以降には、丸みのある角を使用するこのコントロールの新しいテンプレートが含まれます。 詳細については、「 コーナー半径」を参照してください。