kritzelkratz
Topic Author
Posts: 18
Joined: 19 Sep 2013, 17:44

Several setItemSource() with identical sources

23 Oct 2013, 14:16

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?
 
User avatar
sfernandez
Site Admin
Posts: 1911
Joined: 22 Dec 2011, 19:20

Re: Several setItemSource() with identical sources

24 Oct 2013, 12:03

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.
 
kritzelkratz
Topic Author
Posts: 18
Joined: 19 Sep 2013, 17:44

Re: Several setItemSource() with identical sources

25 Oct 2013, 14:18

thanks for the reply.

the first example is what we are trying to do.

is this a limitation of wpf?
 
User avatar
sfernandez
Site Admin
Posts: 1911
Joined: 22 Dec 2011, 19:20

Re: Several setItemSource() with identical sources

25 Oct 2013, 16:50

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
 
User avatar
jsantos
Site Admin
Posts: 2899
Joined: 20 Jan 2012, 17:18
Contact:

Re: Several setItemSource() with identical sources

26 Oct 2013, 19:43

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.

Who is online

Users browsing this forum: No registered users and 1 guest