Search code examples
c#wpfrichtextboxinlineuicontainer

InlineUIContainer delete event in RichTextBox


Is there a way, to get notified when an InlineUIContainer gets deleted in a RichTextBox? Currently I am using the Unload event, which is a problem because the event is also called when I switch between tabs.

My code:

Creating the InlineUIContainer:

InlineUIContainer container = new InlineUIContainer(presenter) { BaselineAlignment = BaselineAlignment.TextBottom };
container.Tag = new TagTextBoxObject(Id, InputText);
container.Unloaded += presenter_Unloaded;

The event, which should not get fired on switching tabs:

void presenter_Unloaded(object sender, RoutedEventArgs e)
{
    Dispatcher.Invoke(
        (Action)delegate()
        {
            TagTextBoxObject item = (TagTextBoxObject)(sender as InlineUIContainer).Tag;

            if (newItems.ContainsKey(item.Id))
            {
                newItems.Remove(item.Id);
            }

            if (!deletedItems.ContainsKey(item.Id))
            {
                deletedItems.Add(item.Id, item.Text);
            }
        });
}

Solution

  • The solution, look wether the parent is loaded:

        void presenter_Unloaded(object sender, RoutedEventArgs e)
        {
            if (this.Parent != null && this.Parent is FrameworkElement)
            {
                if ((this.VisualParent as FrameworkElement).IsLoaded)
                {
                    Dispatcher.Invoke(
                        (Action)delegate()
                        {
                            TagTextBoxObject item = (TagTextBoxObject)(sender as InlineUIContainer).Tag;
    
                            if (newItems.ContainsKey(item.Id))
                            {
                                newItems.Remove(item.Id);
                            }
    
                            if (!deletedItems.ContainsKey(item.Id))
                            {
                                deletedItems.Add(item.Id, item.Text);
                            }
                        });
                }
            }
        }