Page 1 of 1

Several setItemSource() with identical sources

Posted: 23 Oct 2013, 14:16
by kritzelkratz
Hi,

In our application we want to display the same list content twice at the same time in different ListBoxes, one of them is in a pop-up window. However, if we set the ItemSource of those ListBoxes to the same source - a Noesis.Collection - , we get a "Child already has a logical parent"-Exception.
We currently work around this by using two Collections filled with different, but identical PartListItems.
Is there a more elegant way to fix this than using two identical sources?

Re: Several setItemSource() with identical sources

Posted: 24 Oct 2013, 12:03
by sfernandez
Hi,

What is the type of your items in the collection? Because FrameworkElement objects can only have one logical parent in the UI tree. You should use data objects and rely on DataTemplates to represent this data.

I tested the following example that is not correct and throws the "Child already has a logical parent" exception:
Collection collection = new Collection();
collection.Add(new TextBlock("item 1"));
collection.Add(new TextBlock("item 2"));
collection.Add(new TextBlock("item 3"));

ListBox lb1 = root.FindName<ListBox>("lb1");
lb1.SetItemsSource(collection);

ListBox lb2 = root.FindName<ListBox>("lb2");
lb2.SetItemsSource(collection);
This example is failing because TextBlock elements can only be parented once.

Otherwise, the following example works fine:
Collection collection = new Collection();
collection.Add("item 1");
collection.Add("item 2");
collection.Add("item 3");

ListBox lb1 = root.FindName<ListBox>("lb1");
lb1.SetItemsSource(collection);

ListBox lb2 = root.FindName<ListBox>("lb2");
lb2.SetItemsSource(collection);
In this case NoesisGUI internally creates the appropriate elements to correctly represent the string items in the collection. You can override the default representation assigning your own DataTemplate to the ListBox.ItemTemplate property.

Re: Several setItemSource() with identical sources

Posted: 25 Oct 2013, 14:18
by kritzelkratz
thanks for the reply.

the first example is what we are trying to do.

is this a limitation of wpf?

Re: Several setItemSource() with identical sources

Posted: 25 Oct 2013, 16:50
by sfernandez
Yes, it is a limitation of WPF. Here you can find the comments of another example in the MSDN social forums:
http://social.msdn.microsoft.com/Forums ... wo-listbox

Re: Several setItemSource() with identical sources

Posted: 26 Oct 2013, 19:43
by jsantos
Anyway it is a better design if you only have raw text in your collection and have the text block (using your text) in the data template as sergio commented.