Skip to main content

Microsoft Silverlight

Answered Question Access DataTemplate controls in an ItemsControlRSS Feed

(0)

KevKal
KevKal

Member

Member

15 points

5 Posts

Access DataTemplate controls in an ItemsControl

If I have a DataTemplate assigned to the ItemTemplate of an ItemsControl, how can I access the objects inside each container that is created for the Items in ItemsSource?

In Beta 2 I had been accessing the controls inside each container (DataTemplate copy) inside this override in my ItemsControl class:

protected override void PrepareContainerForItemOverride(DependencyObject element, object item)

Previously 'element' would have been equal to StackPanel or anything else from the Template, but at this point all 'element' is ever equal to is a ContentPresenter object.  Unfortunately, the ContentPresenter object does not have the child panels, TextBlocks, etc.  It appears that these objects now get created asynchronously or at a later time during rendering leaving me unable to access/modify them.

Specifically, if my template contains a StackPanel, with a Border inside, and other TextBoxes inside that, etc. I want to be able to change the color of the border for the first control in the list without having to create a new propery on my items and binding the border to it.

Thank you for any help, Kevin.

Yi-Lun Luo - MSFT
Yi-Lun L...

All-Star

All-Star

25052 points

2,747 Posts

Answered Question

Re: Access DataTemplate controls in an ItemsControl

Hello, you can handle the Border's Loaded event. Then check your data source, which is probably a collection. If the Border's DataContext is the first item in the collection, this Border must be in the template for the first item. Then you can modify its properties as you wish. Something like this:

private void Border_Loaded(object sender, RoutedEventArgs e)

{

Border b = (Border)sender;

object o = b.DataContext;

if (o == source[0])

{

b.BorderBrush =
new SolidColorBrush(Colors.Red);b.BorderThickness = new Thickness(2d);

}

}

shanaolanxing - I'll transfer to the Windows Azure team, and will have limited time to participate in the Silverlight forum. Apologize if I don't answer your questions in time.
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities