简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM