如何在TextBox中复制带格式的文本时粘贴值

时间:2016-08-21 17:59:34

标签: xaml text windows-10 uwp paste

我在Windows 10 UWP应用程序中有一个TextBox,看起来像这样。

<TextBox Name="QuoteBox" 
                     MinHeight="160"  
                     TextAlignment="Left" 
                     TextWrapping="Wrap" 
                     Margin="12"
                     RelativePanel.AlignTopWithPanel="True" 
                     RelativePanel.AlignRightWithPanel="True" 
                     RelativePanel.AlignLeftWithPanel="True"
                     IsTabStop="True" KeyDown="InputBox_KeyDown" 
                     Height="{x:Bind MainScrollViewer.ViewportHeight, Converter={StaticResource TwoFifthsConverter}, Mode=OneWay}" />

我要做的是在此TextBox中复制/粘贴一些文本。问题是,当我从电子邮件,网站甚至OneNote复制文本时,文本不会被粘贴。

但是当我在记事本中粘贴该文本并将其从那里复制到TextBox时,它可以正常工作。

我认为这是因为文本包含格式,而TextBox不支持粘贴格式化文本。

有很多这样的问题,但它们涉及非常具体的解决方案和自定义粘贴事件处理程序。

如何在TextBox中的格式化文本中粘贴文本?它需要自定义粘贴事件处理程序吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

所以我为Paste事件创建了一个事件处理程序。基本上我所做的只是将文本从剪贴板复制到文本框Text属性。

它是粘贴事件处理程序documentation page

中的示例的简化
    /// <summary>
    /// Used to paste text when copying formatted text
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void QuoteBox_Paste(object sender, TextControlPasteEventArgs e)
    {
        TextBox quoteBox = sender as TextBox;
        if (quoteBox != null)
        {
            // Mark the event as handled first. Otherwise, the
            // default paste action will happen, then the custom paste
            // action, and the user will see the text box content change.
            e.Handled = true;

            // Get content from the clipboard.
            DataPackageView dataPackageView = Clipboard.GetContent();
            if(dataPackageView.Contains(StandardDataFormats.Text))
            {
                try
                {
                    // Copy text from the clipboard
                    quoteBox.Text = await dataPackageView.GetTextAsync();
                }
                catch
                {
                    // Ignore exception
                }
            }
        }
    }