title: Highlight Search TextBlock
body: <p>My goal is to create a custom TextBlock control that has a new dependency property, SearchText. This property will contain a regular expression. All occurrences of this regular expression in the text of the TextBlock will be highlighted using a custom style (another DP).</p>
  
  <p>My current implementation involves clearing all of the Inline objects in the TextBlock's InlineCollection. I then fill the TextBlock with runs for unhighlighted text and runs for highlighted text with the style applied (this method does not support adding inlines directly to the TextBlock, instead TextBlock.TextProperty has to be used). </p>
  
  <p>Works great, but sometimes I get a strange exception when trying to clear the Inlines: InvalidOperationException: "Cannot modify the logical children for this node at this time because a tree walk is in progress."</p>
  
  <p>This problem seems to be related to <a href="https://stackoverflow.com/questions/486615/invalidoperationexception-when-editing-textblock-inlines-from-inside-ontextchange">this</a> one. I am modifying the inlines in the TextChanged function, but I'm using a flag to avoid infinite recursive edits.</p>
  
  <p>Any thoughts on how to architect this custom control? Is there a better way to do this? How do I get around this exception?</p>
  
  <p>Thanks!</p>