2017-05-05 53 views
0

我使用RichTextBox控件面临challange:如何检索里面的控件(按钮)的RichTextBox内容?

我能够成功段落添加到它在设计时按钮就好了,见下面的XAML:

<RichTextBox x:Name="rtxtStep" HorizontalAlignment="Left" Height="207" Margin="10,32,0,0" VerticalAlignment="Top" Width="427" IsDocumentEnabled="True" KeyUp="richTextBox_KeyUp"> 
      <FlowDocument> 
       <Section FontSize="15"> 
        <Paragraph> 
         Click on this: 

          <Hyperlin k NavigateUri="http://stackoverflow.com">stackoverflow</Hyperlin k> 


        </Paragraph> 

        <Paragraph> 
         <Button Click="Button_Click" Width="143" >Also Click On This</Button> 
         <Button Click="Button_Click" Width="143" >button 2</Button> 
        </Paragraph> 
       </Section> 
      </FlowDocument> 
     </RichTextBox> 

,我能够检索从我的代码的文字就好了,见下图:

private void richTextBox_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter) 
     { 
      TextRange txtrContent = new TextRange(rtxtStep.Document.ContentStart, rtxtStep.Document.ContentEnd); 
      string allContent = txtrContent.Text; 
     } 
    } 

返回:

"Click on this: stackoverflow\r\n \r\n\r\n" 

问题是,我如何检索按钮以及文本?

回答

0

我认为你真的期待太多。 RichTextBox中的FlowDocument是元素的层次结构。你可以做的最好的办法是下降元素树来查找按钮。事情是这样的......

private void richTextBox_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter) 
     { 
      TextRange txtrContent = new TextRange(rtxtStep.Document.ContentStart, rtxtStep.Document.ContentEnd); 
      string allContent = txtrContent.Text; 
      PrintBlocks(rtxtStep.Document.Blocks); 
     } 
    } 

    private void PrintBlocks(IEnumerable<Block> blocks) 
    { 
     foreach(Block b in blocks) 
     { 
      Trace.WriteLine("Found " + b.GetType().Name); 
      if(b is Section) 
      { 
       PrintBlocks((b as Section).Blocks); 
      } 
      else if(b is Paragraph) 
      { 
       PrintInlines((b as Paragraph).Inlines); 
      } 
     } 

    } 

    private void PrintInlines(IEnumerable<Inline> inlines) 
    { 
     foreach(Inline i in inlines) 
     { 
      if(i is InlineUIContainer) 
      { 
       PrintInlineUIContainer(i as InlineUIContainer); 
      } 

     } 
    } 
    private void PrintInlineUIContainer(InlineUIContainer i) 
    { 
     Trace.WriteLine("Found " + i.Child.GetType().Name + " " + i.Child.ToString()); 
    } 

为了您的XAML,产生这种输出...

Found Section 
Found Paragraph 
Found Paragraph 
Found Button System.Windows.Controls.Button: Also Click On This 
Found Button System.Windows.Controls.Button: button 2 

但是你知道这已经。你似乎想要一些集成格式的文本和按钮(可能是HTML?)。我认为你需要编写自己的代码才能做到这一点。