Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top