如何使用其中的控件(按钮)检索RichTextBox内容?

时间:2017-05-05 20:38:08

标签: wpf richtextbox

我正面临使用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"

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

1 个答案:

答案 0 :(得分: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?)。我想你需要编写自己的代码才能做到这一点。