Home > Mobile >  Impossible to cast string object to class object
Impossible to cast string object to class object

Time:04-23

I am remaking an old program of mine in Visual Studio and in this program I have a list of objects that can be added and removed from a List. I'm using the .WPF framework so when I want to remove one of these objects, I display in a new window each one object's identifying string (I hope to be more clear once I add the code reference).

The problem is that when I try to remove one of these object from my list, I have to cast the selected item from my listView, into a class object (because my list is made of these class objects). When I do the casting it says that it cannot cast objects of type 'String' into 'myClass'

I'll leave here the window.cs part where it does the listView selection changed

private void myObjectsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     myClass ObjectSelected = (myClass)ObjectList.SelectedItem;
     MainWindow mainWindow = new MainWindow();
     mainWindow.removeFromList(ObjectSelected);
}

And, if it may be of any use, the window.xaml ListView

<ListView x:Name="bookList"
                  Margin="10"
                  SelectionChanged="bookList_SelectionChanged"/>

CodePudding user response:

You're doing it wrong. If I understand correctly, e will have the selected item's string id. Then you do ObjectSelected.Remove(a => a.Id == e.Id);

  • Related