Search code examples
wpfitemscontrol

WPF ItemsControl.ItemsTemplate Code Behind


I am currently using an ItemsControl template that binds to the the ViewModel to present a collection of objects. I have a ToggleButton as part of the template. I would like to access the object that is bound to that UI item in the collection in the code behind.

Here is the code that I have in place:

<ItemsControl.ItemTemplate>
   <DataTemplate>
      <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">
           <ToggleButton Cursor="Hand"
                         IsChecked="{Binding IsActive, Mode=TwoWay}"
                         IsEnabled="{Binding CanToggleOnProfile}"
                         Style="{StaticResource ProfileToggleButtonStyle}" 
                         PreviewMouseLeftButtonUp="OnProfileToggle">

I would like to in my code behind on the OnProfileToggle call, access that particular object in the DataTemplate and do some stuff with it, but I can't seem to figure out how to access it (what index it is at in the collection, etc).


Solution

  • You will find your particular object in the DataContext of the sender:

    private void OnProfileToggle(object sender, MouseButtonEventArgs e)
    {
        ToggleButton button = sender as ToggleButton;
        object yourItem = button.DataContext;
    }
    

    Of course you have to cast yourItem to your item class.