从 WPF 中的富文本框中删除表定义

本文关键字:删除 定义 WPF 文本 | 更新日期: 2023-09-27 17:57:50

我的视图中有一个 RichTextBox 控件。我正在使用代码隐藏(仅限 UI 逻辑(来格式化我的 RichTextBox 中的 RTF,该 RTF 正在从实例化 TextRange 的"格式"按钮单击事件中工作:

private void _btnFormat_Click(object sender, RoutedEventArgs e)
{
    TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
    rangeOfText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
    rangeOfText.ApplyPropertyValue(TextElement.FontSizeProperty, "12");
    rangeOfText.ApplyPropertyValue(TextElement.FontFamilyProperty, "Arial");
    rangeOfText.ApplyPropertyValue(TextElement.FontStyleProperty, "Normal");
    rangeOfText.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
 }

我还想删除 RTF 中的任何表。我可以从 Table 类中使用相同的方法来从我的 RichTextBox 中删除表吗?谢谢

从 WPF 中的富文本框中删除表定义

你必须爬下Blocks并得到后代FlowDocument并获取所有Tables,然后将它们从其Parent中删除。

好的,如果有人试图实现这一目标,我认为这是不可能的。也许您可以遍历 Rtf 字符串中的简单表并删除标签,但如果您无法确定用户输入,则 Rtf 太复杂了。因此,这是我的解决方案(各种...

    private void _btnFormat_Click(object sender, RoutedEventArgs e)
    {              
       TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
      rangeOfText.ApplyPropertyValue(Table.BorderThicknessProperty, "3");
      rangeOfText.ApplyPropertyValue(Table.BorderBrushProperty, Brushes.Red);
     }

在"格式"按钮单击事件中,我将表格边框设置为红色。在我保存回数据库方法时,我使用了这个简单的 if 语句:

private void SaveToDbCommandAction()
{
    if(PastedText.Contains("trowd"))
    {
        Xceed.Wpf.Toolkit.MessageBox.Show("Cannot save Article. Please remove pasted tables");          
    }
    else
    {
        SaveToDb(RTBText);
    }            
}

因此,当用户粘贴到表格中时,他们会通过红色单元格边框收到警告。如果他们粘贴具有不可见边框的表格并且实际上看不到该表格,这将特别有用。然后,If 语句确定 Rtf 字符串是否包含"trowd"标记,从而阻止保存。