2

I'm trying to correctly remove a UIElement from an InlineUIContainer in order to use it in another Panel but the program keeps crashing with this message "Specified Visual is already a child of another Visual or the root of a CompositionTarget.".

I've created a small application to illustrate my pain. In this program, once Randy the button is killed\deleted by his girlfriend, he doesn't still detach from his parent, whom I got find out was UIElementIsland. And then any attempt to add Randy as the child of anything else crashes the application (The Apocalypse Button proves my point :) ). You can click to check Randy's parents before\after deleting Randy to notice that he is constantly under UIElementIsland as a child, If he is detached the whole problem\apocalypse should be averted.

It's a Funny application so copy and compile even if it's just for the fun! Any help\ideas would be appreciated!

THE C# Part:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace DetachingfromUIElementIsland
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        int t = 0;

        static string[] info = new string[] { "Okay, Lets have a look...", "Checking."
            , "Checking..", "Checking...", "Seen it!"  };

        /// <summary>
        /// Makes the App fancy :)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer_Tick(object sender, EventArgs e)
        {
            display.Text = info[t];

            if (t == 0)
                timer.Interval = new TimeSpan(0, 0, 0, 0, 300);

            t++;
            if (t >= 4)
            {
                t = 0;
                timer.Stop();
                display.Text = GetRandysParent();
            }
        }

        private void deleteRandy_Click(object sender, RoutedEventArgs e)
        {
            // This might be the bug.
            // Maybe there's a better way to do this.
            // If there was a VisualTreeHelper.Remove().
            randy_container.Child = null;

            display.Text = "Haha! I just killed Randy!!! He'll never get the chance"
                + "\n to hurt another woman again!";
            display.Background = Brushes.Violet;
            end.Visibility = System.Windows.Visibility.Visible;
        }

        DispatcherTimer timer = null;

        /// <summary>
        /// Check if Randy is Still attached to UIElementIsland
        /// </summary>
        /// <returns></returns>
        private string GetRandysParent()
        {
            // Check the visual tree to see if randy is removed properly
            DependencyObject dp = VisualTreeHelper.GetParent(randy);
            string text = string.Empty;
            if (dp != null)
            {
                display.Background = Brushes.LightGreen;
                text = "Randy's Dad is Mr " + dp.ToString();
            }

            else
            {
                // This should be what you'll get when the code works properly
                display.Background = Brushes.Red;
                text = "Weird...Randy doesn't seem to have a dad...";
            }
            return text;
        }

        private void findParents_Click(object sender, RoutedEventArgs e)
        {  
            display.Background = Brushes.Yellow;

            // Creates a timer to display some fancy stuff
            // and then Randy's.
            // Just to prove to you that this button actually works.
            timer = new DispatcherTimer();
            timer.Start();
            timer.Tick += timer_Tick;
            timer.Interval = new TimeSpan(0, 0, 0, 0, 700);
        }

        private void randy_Click(object sender, RoutedEventArgs e)
        {
            // Get Randy to introduce himself
            display.Text = "Hi, I'm Randy!!!";
            display.Background = Brushes.Orange;
        }

        private void end_Click(object sender, RoutedEventArgs e)
        {
            // If randy is removed properly, this would not crash the application.
            StackPanel s = new StackPanel();
            s.Children.Add(randy);
            // CRASH!!!
        }
    }
}

The XAML:

<Window x:Class="DetachingfromUIElementIsland.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <FlowDocument IsEnabled="True" x:Name="document">
        <Paragraph>
            <InlineUIContainer x:Name="randy_container">
                <!--Meet Randy-->
                <Button Name="randy" Content="I am a Randy, the button" Click="randy_Click" ToolTip="Meet Randy"/>
            </InlineUIContainer>
            <LineBreak/>
            <LineBreak/>
            <InlineUIContainer x:Name="container2">
                <!--Meet Randy's Ex Girlfriend-->
            <Button Name="deleteRandy" Content="Randy dumped me for another girl :(, click me to delete him" Click="deleteRandy_Click" ToolTip="Meet Randy's Ex Girlfriend"/>
            </InlineUIContainer>
            <LineBreak/>
            <LineBreak/>
            <InlineUIContainer x:Name="container3">
                <!--He can help you find Randy's Parents-->
            <Button Name="findParents" Content="Click me to find randy's parents" Click="findParents_Click" ToolTip="He can help you find Randy's Parents"/>
            </InlineUIContainer>
            <LineBreak/>
            <LineBreak/>
            <InlineUIContainer x:Name="Apocalypse">
                <!--End the world, Crash the application-->
                <Button x:Name="end" Content="Avenge Randy's Death" Click="end_Click" ToolTip="End the world, Crash the application" Visibility="Hidden"/>
            </InlineUIContainer>
        </Paragraph>
        <Paragraph>
            <InlineUIContainer>
                <TextBlock x:Name="display" Foreground="Black"/>  
            </InlineUIContainer>
        </Paragraph>
    </FlowDocument>
</Window>

The whole code was supposed to be shorter than this, but I spiced it up to make it a bit fun. Hope I brightened someone's day a little. But still, help me :).

Answer: Derive from Randy's InlineUIContainer as follows:

    public class DerivedInlineUIContainer : InlineUIContainer
    {   
        public DerivedInlineUIContainer()
        {

        }

        public void RemoveFromLogicalTree(FrameworkElement f)
        {
            this.RemoveLogicalChild(f);
        }
    }

Now you could kill Randy properly this time, and add him to UIElement heaven (The StackPanel):

    randy_container.RemoveFromLogicalTree(randy);
    IDisposable disp = VisualTreeHelper.GetParent(randy) as IDisposable;
    if (disp != null)
        disp.Dispose();

    // Poor Randy is going to heaven...
    StackPanel heaven = new StackPanel();
    heaven.add(randy);

Thanks everyone.

Prince Owen
  • 1,225
  • 12
  • 20

3 Answers3

1

Removing the visual parent doesn't seem to help:

private void end_Click(object sender, RoutedEventArgs e)
{
    IDisposable disp = VisualTreeHelper.GetParent(randy) as IDisposable;
    if (disp != null)
        disp.Dispose();

    DependencyObject parent = VisualTreeHelper.GetParent(randy);
    if (parent == null)
        MessageBox.Show("No parent");

    // If randy is removed properly, this would not crash the application.
    StackPanel s = new StackPanel();
    s.Children.Add(randy);
}

So you could either create a new Button:

public MainWindow()
{
    InitializeComponent();
    randy_container.Child = CreateRandyButton();
}

private void end_Click(object sender, RoutedEventArgs e)
{
    StackPanel s = new StackPanel();
    s.Children.Add(CreateRandyButton());
}

private Button CreateRandyButton()
{
    Button button = new Button { Name = "randy", Content = "I am a Randy, the button", ToolTip = "Meet Randy" };
    button.Click += randy_Click;
    return button;
}

...or simply hide it as suggested by @Sinatr.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Yes, it's still crashing, but the message has changed to "Specified element is already the logical child of another element. Disconnect it first.". I'll see how I can solve that – Prince Owen Aug 21 '17 at 10:44
  • It should not crash when you do: s.Children.Add(CreateRandyButton()); – mm8 Aug 21 '17 at 10:45
  • 1
    Hey! Nice work!!! I derived from the `InlineUIContainer` and called `RemoveLogicalChild()`. Together with your suggestion about `Dispose()`. And it worked. Thanks a lot! – Prince Owen Aug 21 '17 at 11:28
0

It's funny, but also very noisy. You would get answer much faster if your demo is short.

Instead of removing/adding visual you can simply hide/show it:

void deleteRandy_Click(object sender, RoutedEventArgs e) =>
    randy.Visibility = Visibility.Hidden;

void end_Click(object sender, RoutedEventArgs e) =>
    randy.Visibility = Visibility.Visible;

This way you are not playing with visual tree in unrecoverable way. You can use MVVM + data templates or x:Shared=False resources if you really want to remove UI element and then add new one.

Sinatr
  • 20,892
  • 15
  • 90
  • 319
0

I found a workaround in case the parent is still a UIElementIsland. Since it implements IDisposable, you can clear its children that way:

var parent = VisualTreeHelper.GetParent(element);
if (parent is IDisposable uiElementIsland)
{
   uiElementIsland.Dispose();
}

It's not nice, but it works.

Lennart
  • 9,657
  • 16
  • 68
  • 84