1

I'm getting InvalidOperationException somewhat randomly in the following code, what's a good way to fix it?

public class ParsedTextBlock : TextBlock
{
    static ParsedTextBlock() {
        TextProperty.OverrideMetadata(typeof(ParsedTextBlock),
            new FrameworkPropertyMetadata("No Text Set",
                FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
                OnTextChanged)
            );
    }

    private static void OnTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        ParsedTextBlock control = (ParsedTextBlock)obj;
        control.Inlines.Clear();
        control.Inlines.Add(new Run("test " + args.NewValue as string))
    }
}
Eric
  • 851
  • 7
  • 16

1 Answers1

0

I don't believe changing the text from within the text changed event would be a good idea. This would cause the event to fire recursively and eventually generate a stack overflow... how ironic :)

csharptest.net
  • 62,602
  • 11
  • 71
  • 89
  • The text changed is for the container control, it's changing the text of a sub-control, not itself. – Eric Sep 07 '09 at 18:06
  • Never mind, I see what you mean, you're probably right about that. – Eric Oct 30 '09 at 03:54
  • I'm hitting the same exception while doing something similar. I eliminated the stack overflow problem by added a boolean "processing" flag. If the change is already being processed, I skip the processing on the change notification. Not sure if there's a better way to do this, but I'm still hitting this exception. – Josh G Oct 06 '10 at 14:37