【问题标题】:Remove text formatting on paste in WPF RichTextBox?在 WPF RichTextBox 中粘贴时删除文本格式?
【发布时间】:2020-10-30 16:53:14
【问题描述】:

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 号。有没有更好的方法来解决这个问题或设置粘贴字符串的字体大小?

谢谢

【问题讨论】:

  • 粘贴是字符串类型。您不需要使用 paste.ToString()。
  • 尝试 Clipboard.GetText() 而不是 Clipboard.GetData("Text")。这可能会解决您的问题。
  • 是的,这些只是我忘记更改的一些代码。结果一样...

标签: c# wpf xaml mvvm richtextbox


【解决方案1】:

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

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.
    }

【讨论】:

  • 不,我需要清除剪贴板,否则未格式化的副本会附加到字符串中。不,我需要解决粘贴字符串的大小...
  • 经过进一步检查,这似乎与粘贴的文本未以 RTF 格式插入 RTB 有关...
【解决方案2】:
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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2011-05-14
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多