Search code examples
wpftextblockremovechild

How to remove children of TextBlock form specific child?


Assuming I have a TextBlock like below. At runtime I want remove/delete all its children from the first LineBreak onward (include LineBreak), keep the before. How I can do it? Thank!

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

I did this and error :)

    bool begin = false;

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

Solution

  •    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 );
       }