Stefan
Stefan

Reputation: 7

C# Can't get values from Listview items

I'm trying to get Values from clicked items in my Listview but for some reason I can't access any variables from my class.

Here is my listview:

<ListView x:Name="lvGames" Margin="0,29,583.8,-0.2" SelectionChanged="MySelectionChanged">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" Width="149" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

Class which is attached to the Listview:

namespace GameLauncher.Classes
{
    class Game
    {
        public bool CheckBoxes { get; set; }

        public string Name { get; set; }

        public string Path { get; set; }

        public int time { get; set; }
    }
}

SelectionChanged event:

private void MySelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("Selected: " + e.AddedItems[0]);
}

This SelectionChanged event returns the right class path GameLauncher.Classes.Game But I can't acces e.AddedItems[0].Name; for example. Why can't I access any variables from my Game class from here? I also tried lvGames.SelectedItems[0].Name wich didn't work either. The only options I have are Equals, GetHashCode, GetType and ToString.

I hope someone knows what I'm doing wrong here.

Thanks for reading/helping!

Upvotes: 0

Views: 135

Answers (1)

John Paul
John Paul

Reputation: 837

SelectionChangedEventArgs.AddedItems returns an IList. You need to cast to game. So you need to do:

Game game = e.AddedItems[0] as Game;
MessageBox.Show("Selected: " + game.Name);

Upvotes: 3

Related Questions