Ilia Stoilov
Ilia Stoilov

Reputation: 632

Detecting which item was clicked in a ListView with a DataTemplate

I have a ListView with a simple DataTemplate - a image and a text.

        List<MenuItem> Items = new List<MenuItem> { 
            new MenuItem ("TRADE","menuTradeIconBig.png"), 
            new MenuItem ("PROFILE","menuProfileIconBig.png"),
        };

        var listView = new ListView ();
        var viewTemplate = new DataTemplate(typeof(MenuCell)); //MenuCell contains a grid
        listView.ItemTemplate = viewTemplate; 
        listView.ItemsSource = Items; 

If the ListView is filled with strings, I can easily do this:

        listView.ItemTapped += (sender, e) => 
        {
            MenuHandler(e.Item.ToString()); //My function to process item clicks
        };

But now, when I use this, the response converted ToString() is "MyProjectName.MenuItem".

How can I get the clicked item?

Upvotes: 0

Views: 451

Answers (1)

Ilia Stoilov
Ilia Stoilov

Reputation: 632

I figured it out:

listView.ItemTapped += (sender, e) => 
{
        MenuHandler((MenuItem)e.Item);
};

public void MenuHandler(MenuItem item) 
{
            MenuItem selected = item;
//do whatever you want with the object
}

Upvotes: 3

Related Questions