Getting the Item container corresponding to the selected item in XAML – Windows Store App

Getting the Item container corresponding to the selected item in XAML – Windows Store App

While building Apps using XAML, in many instances you may encounter this problem where you need to get an access for the container element from an ItemControl elements. For an example, you have GridView Control, and which has some grouped element as part of Item DataTemplate. If you handle only the GridItemClick event with command pattern (Using ICommand), you won’t be able to get access of the original sender directly (as it passes only ItemClickEventArgs). Which was the child element control of the GridView. On those scenarios you can use ContainerFromItem method that’s return the actual container corresponding to the specified item.

The ContainerFromItem method returns DependencyObject by accepting the item passed into it.

  public void OnGridItemClick(ItemClickEventArgs obj)
                if (obj != null )
                    GridView gridView = (GridView)obj.OriginalSource;
                    var selectedItem = gridView.<strong>ContainerFromItem</strong>(obj.ClickedItem);
                    item = (GridViewItem)selectedItem;
                  // Do stuff here

As shown in the above code block, OnGridItemClick, command execute on click of GridItems. where OnGridItemClick is nothing but a DelegateCommand defined as follows.

      public ICommand GridViewItemClickCommand { get; private set; }
  GridViewItemClickCommand = new DelegateCommand<ItemClickEventArgs>(OnGridItemClick);

And which is being called as,

Command="{Binding GridViewItemClickCommand , ElementName=pageRoot}" CommandParameter="{Binding ClickedItem}" />

This ContainerFromItem is quite helpful when you want to handle some of the operation depends on the sender object, and want to operate something on the UIElement.

You can also use ContainerFromIndex(), that does the same operation by accepting index rather the item.

Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.