Alex Cube
Alex Cube

Reputation: 442

WPF has different behavior on different environment?

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        RichTextBox myRTB = new RichTextBox();
        ListViewItem lvi1 = new ListViewItem();
        ListViewItem lvi2 = new ListViewItem();
        lvi1.Content = myRTB;
        lvi2.Content = myRTB;

        this.lstView1.Items.Add(lvi1);
        this.lstView2.Items.Add(lvi2);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Two machines:
Machine 1: Windows 7 32bit, .net4.0 installed
Machine 2: Windows 8 64bit, .net4.0/4.5 installed

The above code always crash on machine 1, with exception "Specified element is already the logical child of another element, Disconnect it first.

But, it works on machine 2.(the content of lvi2 is actually empty)

Can someone have detailed explanation, why it happens?(Note: the test app is built with VS2010, .net 4.0)

Added: the following code has the same issue(work on machine 2, not machine 1)

    try
    {
        RichTextBox myRTB = new RichTextBox();
        ListViewItem lvi1 = new ListViewItem();               
        lvi1.Content = myRTB;
        this.lstView1.Items.Add(lvi1);
        this.lstView1.Items.Remove(lvi1);
        ListViewItem lvi2 = new ListViewItem();
        lvi2.Content = myRTB;
        this.lstView2.Items.Add(lvi2);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

Upvotes: 3

Views: 286

Answers (1)

New Dev
New Dev

Reputation: 49590

You shouldn't be assigning the same control as a child/content of two different controls.

As for your question, there might be a change in .NET framework 4.5 that relaxed or modified the behavior in this situation. Even though your app targets 4.0, it still executes in .NET 4.5 runtime. In other words, .NET 4.5 replaces .NET 4.0 as opposed to working side-by-side.

Upvotes: 6

Related Questions