Silverlight, getting ItemSource data from data template programmatically

337 views Asked by At

I've got an ItemsControl with an ItemsSource of Hours. I represent each item by a border (in the data template).

Now, each of those border has an hour data, and i want to retrieve that in code behind. is it even possible?

my code example:

<ItemsControl x:Name="dayHours">
     <ItemsControl.ItemTemplate>
          <DataTemplate>
               <Border Name="dayHourBorder" Height="30" BorderBrush="#B0B6BE" Width="193" BorderThickness="1,0,1,1" Background="AliceBlue" Tag="{Binding Index}" />
          </DataTemplate>
     </ItemsControl.ItemTemplate>
 </ItemsControl>

And in the naive way, I would expect a code like:

(sender as Border).hourTime;
1

There are 1 answers

0
ColinE On BEST ANSWER

From your code, I am guessing that you are interested in finding the 'hourTime' in an event handler? When an ItemsControl creates an 'instance' of your DataTemplate for each item, it sets the DataContext of the template to the item itself. Therefore the following should work:

Border border = sender as Border;
MyItemType item = border.DataContext as MyItemType;
var hourTime = item.hourTime;