Question

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);
    }
Was it helpful?

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 );
   } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top