删除粘贴在 WPF 富文本框中的文本格式

本文关键字:文本 格式 WPF 删除 | 更新日期: 2023-09-27 17:57:02

vs2010,WPF .NET 4.5在这里。

我有一个RichTextBox。文本设置为 Arial,大小为 12:

    <xctk:RichTextBox  DataContext="{StaticResource EditorViewModel}" Grid.Row="1" 
        Height="296" HorizontalAlignment="Center" SpellCheck.IsEnabled="True"       Margin="6,145,6,0" 
        Name="richTextBoxArticleBody"  VerticalAlignment="Top" Width="962" Grid.RowSpan="2"  
        BorderBrush="Silver" BorderThickness="1" AcceptsTab="True" FontFamily="Arial" FontSize="12"
        Text="{Binding PastedText, UpdateSourceTrigger=PropertyChanged}" />

我想从粘贴中删除所有格式到我的RichTextBox.我的视图中有一个"粘贴"按钮,该按钮绑定到FormatPastedText命令:

 private void FormatPastedTextCommandAction()
    {
        string paste = (string)Clipboard.GetData("Text");
        Clipboard.SetText(paste);
        PastedText += paste.ToString();
        Clipboard.Clear();          
    }

这几乎有效,除了粘贴的文本不是以字体大小 12 显示,而是以大约 15 显示。键入的文本的格式为预期大小 12。有没有更好的方法可以解决这个问题或设置粘贴字符串的字体大小的方法?

谢谢

删除粘贴在 WPF 富文本框中的文本格式

试试这个,这可能会解决你的问题。这可能无法解决问题。但是对代码中作为注释提到的代码有一些改进。

private void FormatPastedTextCommandAction()
    {
        string paste = Clipboard.GetText();     // casting is not required if this function is used
        // Clipboard.SetText(paste);            // This line is reduntant
        PastedText += paste;                    // no need to call ToString()
        // Clipboard.Clear();                      // You should not clear the Clipboard, as the user may want to paste the data in some other window/application.
    }
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.KeyCode == Keys.V) && e.Control && !e.Alt && !e.Shift)
    {
        // remove text formatting in the text in clipboard
        if (Clipboard.ContainsText(TextDataFormat.Html) || Clipboard.ContainsText(TextDataFormat.Rtf))
        {
            string plainText = Clipboard.GetText();
            Clipboard.Clear();
            Clipboard.SetText(plainText);
        }
    }
}