user3911053
user3911053

Reputation:

How to access Properties of Objects supplied to event handler? (Can view when debugging, but not with Intellisense.)

I am trying to find which item is selected in a ListView. When the selection is changed, I run the following code:

private void Change_CurrentConnection(object sender, SelectionChangedEventArgs e)
{
    var d = e.AddedItems[0];
}

And you can see here what d is: enter image description here

My question is, how can I access the Id, Name, and Url properties? (The properties are strings from a custom class. The ListView is bound to a collection of objects generated from that class.)

Upvotes: 0

Views: 75

Answers (2)

MethodMan
MethodMan

Reputation: 18863

you can do this as the following also

Connection lstViewItem = (Connection)YourListView.SelectedItems[0];

Upvotes: 1

Laurence Adams
Laurence Adams

Reputation: 366

You need to cast the item as your class, which appears to be called Connection? You should first check to see if the object you are casting is actually of the type you wish to cast it to:

if (e.AddedItems[0] is Connection)
{
    Connection toAccess = e.AddedItems[0] as Connection;

    // Here you can access the properties directly
    string myUrl = toAccess.Url;
}

This way we avoid an InvalidCastException.

Upvotes: 3

Related Questions