6

我有一个 WPF FlowDocument,它有几个 InlineUIContainers,这些是简单的 InlineUIContainers,其中包含一个样式化的按钮,其中包含 Button.Content 中的一些文本。当我将包含按钮的文本和 InlineUIContainer 从 FlowDocument 复制到 TextBox 时,不会复制按钮。

可以以某种方式转换内联按钮或将按钮转换为粘贴文本数据中的文本。我曾尝试使用 FlowDocument.DataObject.Copying 事件,但我似乎找不到任何关于如何使用它的好示例,或者即使这是正确的方向。

谢谢

4

1 回答 1

15

I had the same problem and managed to get something like the following to work:

public class MyRichTextBox : RichTextBox
{
    public MyRichTextBox()
        : base()
    {
        CommandManager.RegisterClassCommandBinding(typeof(MyRichTextBox),
                                                   new CommandBinding(ApplicationCommands.Copy, OnCopy, OnCanExecuteCopy));
    }

    private static void OnCanExecuteCopy(object target, CanExecuteRoutedEventArgs args)
    {
        MyRichTextBox myRichTextBox = (MyRichTextBox)target;
        args.CanExecute = myRichTextBox.IsEnabled && !myRichTextBox.Selection.IsEmpty;
    }

    private static void OnCopy(object sender, ExecutedRoutedEventArgs e)
    {
        MyRichTextBox myRichTextBox = (MyRichTextBox)sender;
        Clipboard.SetText(GetInlineText(myRichTextBox));
        e.Handled = true;
    }

    private static string GetInlineText(RichTextBox myRichTextBox)
    {
        StringBuilder sb = new StringBuilder();
        foreach (Block b in myRichTextBox.Document.Blocks)
        {
            if (b is Paragraph)
            {
                foreach (Inline inline in ((Paragraph)b).Inlines)
                {
                    if (inline is InlineUIContainer)
                    {
                        InlineUIContainer uiContainer = (InlineUIContainer)inline;
                        if (uiContainer.Child is Button)
                            sb.Append(((Button)uiContainer.Child).Content);
                    }
                    else if (inline is Run)
                    {
                        Run run = (Run)inline;
                        sb.Append(run.Text);
                    }
                }
            }
        }
        return sb.ToString();
    }
}

Of course this is very simplistic - you would probably create a subclass of Button and define an interface-function like "GetCopyToClipboardText" instead of having the "how to get text from a button"-code inside the richtextbox.

The example copies all text inside the richtextbox - it would be more usefull if only the selected part of the textbox was copied to the clipboard. This post gives an example of how to achive that.

于 2010-03-05T13:36:44.080 回答