tags:

views:

113

answers:

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))
    }
}
A: 

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
The text changed is for the container control, it's changing the text of a sub-control, not itself.
Eric
Never mind, I see what you mean, you're probably right about that.
Eric
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