2010-09-21 66 views
1

我有一個WPF應用程序,用戶可以在RichTextBox中粘貼一些Word數據......但如果這個單詞數據有圖像,我需要刪除它,我該怎麼做呢? 由於FlowDocument是xml,也許做一些linq魔術可以做到這一點,但我不知道如何:/從RichTextBox中移除圖像FlowDocument

+0

LogicalTreeUtility用於獲取FlowDocument中的特定元素,可能在此處可以使用:http://www.eggheadcafe.com/tutorials/aspnet/233d3397-0388-473c-8473-721a40cf910c/wpf- custom-find-control-for-flowdocuments.aspx – 2010-09-23 21:05:55

回答

0

有一個名爲WordtoXAML轉換器(http://wordtoxaml.codeplex.com)的工具。您可以使用它將Word文檔內容轉換爲XAML,使用正則表達式匹配來識別圖像,然後將其去除。

+0

那麼,從Word粘貼的RichTextBox託管FlowDocument將執行轉換,因此向解決方案添加第三方工具不會使此任務變得更加簡單。 – 2010-09-23 21:02:34

0

下面的代碼將做你想要的。雖然它可能有點浪費(它會查看整個文檔而不是剛剛粘貼的位),但它是唯一的方法,因爲有時RichTextBox在指示最近繪製的範圍時不準確:

public class MyTextBox : RichTextBox 
    { 

     public MyTextBox() 
     { 
      CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, Paste)); 
     } 

     protected virtual void Paste(object sender, ExecutedRoutedEventArgs e) 
     { 
      Paste(); 

      foreach (var image in FindImages()) 
      { 
       if (image.SiblingInlines != null) 
       { 
        image.SiblingInlines.Remove(image); 
       } 
      } 
     } 

     IEnumerable<InlineUIContainer> FindImages() 
     { 
      var result = new List<InlineUIContainer>(); 
      var blocks = Document.Blocks; 
      for (TextPointer position = blocks.FirstBlock.ElementStart; position != null && position.CompareTo(blocks.LastBlock.ElementEnd) != 1; position = position.GetNextContextPosition(LogicalDirection.Forward)) 
      { 
       InlineUIContainer element = position.Parent as InlineUIContainer; 
       if (element != null && element.Child is Image) 
       { 
        result.Add(element); 
       } 
      } 
      return result; 
     } 
    }