views:

344

answers:

1

I have an <ItemsControl> with a custom <DataTemplate> (and also a custom <ItemsPanelTemplate> that is just a WrapPanel), bound via ItemsSource to a simple observable collection of strings.

The DataTemplate consists simply of an instance of a custom UserControl whose properties are bound to the string via {Binding}.

The problem is since my data items are just strings, I need to access the instances of my UserControl directly programmatically, but I can't seem to figure out how!

I've tried:

var item = tagBar.Items[ tagBar.Items.Count - 1 ];

...but that just returns the string. Also:

var item2 = tagBar.ItemContainerGenerator.ContainerFromIndex( tagBar.Items.Count - 1 );

...returns a ContentPresenter, and I can't figure out what to do with the ContentPresenter to get to the instance of my UserControl.

??

This is similar to this question, but it was never properly answered, and was also specific to Silverlight whereas this is WPF.

+2  A: 

The answer I've posted over here deals with focusing an element inside a DataTemplate, but it should provide the code you need. It involves using the FindName method on your DataTemplate to find a control within it. If you give your UserControl a name you should be right.

Matt Hamilton
Excellent, that did it! The key was passing `item` (or rather `item2` in my above code) back into `tagBar.ItemTemplate.FindName()` (and of course, giving the `UserControl` a name to be found by).I'll also be careful with the IsLoaded bit, though that's kind of lame that it's needed.Thanks!
chaiguy
Apparently backticks don't work in comments. :P
chaiguy
@chaiguy1337 -- it looks like backtick support has been added since you wrote that, as the text comes through with formatting now.
Drew Noakes