views:

186

answers:

1

I have two classes A & B, and a listbox. I assign listBox.ItemsSource equal to a collection of objects of type A. The listbox items are visualized using silverlight data templating, see http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx and http://www.codeproject.com/KB/WPF/UserControlAsDataTemplate.aspx for example. The listbox.ItemTemplate is a DataTemplate that uses class B to visualize the listbox items. Now, in my code-behind, inside any method of class B, if I do this.DataContext, it points to an object of type A. Thus, given an object of type B, I can find the corresponding object of type A. So far so good. My question is, given an object of type A, how can I navigate to the corresponding object of type B? Is this even possible in SL?

+1  A: 

On the surface of things you should be able to use code like this:-

  ListBoxItem item = (ListBoxItem)myListBox.ItemContainerGenerator.ContainerFromItem(myTypeA);
  MyTypeB typeB = (MyTypeB)item.Content;

However this may not work in all cases. There is no guarantee that the ListBox has even generated a ListBoxItem for every object in the ItemsSource.

AnthonyWJones
Absolutely -- there are many cases where virtualization and other timing factors that the first line in you example code may return a null. There are generally other safer ways to accomplish the same thing that are guaranteed to work, so possibly a clarification in what's needed would help.
WPCoder
@WPCoder: I'd be interested in a method that is "guaranteed to work"? The reason why I demonstrated the above instead of a "guaranteed" one is because I don't know of any. After all if the appropriate instance of typeB doesn't exist then there is nothing much you can do about it. I guess what the OP would need to do would depend on why he needed it in the first place.
AnthonyWJones