假设我有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);
}
答案 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 );
}