InlineUIContainer delete event in RichTextBox

589 views Asked by At

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);
            }
        });
}
2

There are 2 answers

0
BendEg On BEST ANSWER

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);
                        }
                    });
            }
        }
    }
1
Yoh Deadfall On

You can unsubscribe from the Unload event when the TabControl.SelectionChanged is fired. And subscribe again when the specific tab is selected.

But I think that better way is to create a custom control which will hosts a TextBox and an ItemsControl and do not use RichTextBox.