如何删除TextBlock表单特定子项的子项?

时间:2013-11-16 13:10:05

标签: wpf textblock removechild

假设我有TextBlock,如下所示。在运行时,我希望从第一个LineBreak开始删除/删除所有子项(包括LineBreak),保留之前。我怎么能这样做?谢谢!

<TextBlock Name="tbl">
    <Run/>
    ....
    <Run/>
    <LineBreak/>
    <Run/>
    ....
    <Run/>
</TextBlock>

我这样做并且错误:)

    bool begin = false;

    foreach (var item in tbl.Inlines)
    {
        if (item is LineBreak) begin = true;
        if (begin) tbl.Inlines.Remove(item);
    }

1 个答案:

答案 0 :(得分:2)

   List<Inline> _inlinesToRemove = new List<Inline>();      
   bool lineBreakFound = false;
   for (int i = 0; i < VisualTreeHelper.GetChildrenCount(textBlock); i++)
   {
       Inline _inline = (Inline)VisualTreeHelper.GetChild(textBlock, i);

       if (_inline is LineBreak)
       {
           lineBreakFound = true;
           _inlinesToRemove.Add(_inline); // remove the line break as well 
       }
       // not use else here
       if (lineBreakFound)
       {
            _inlinesToRemove.Add(_inline);
       }
   }

   foreach( Inline _inline in _inlinesToRemove)
   { 
       textBlock.Inlines.Remove(_inline );
   }