I\'m trying to select object from listview and cast to my custom object like this
MyObject foo = (MyObject)MyListView.SelectedItems[0];
but thi
Default ListView
is not data-bindable (i.e. you can't assign some objects as data source of list view). It contains ListViewItem
objects, which cannot be casted to your data type. That's why you getting this error.
If you want to get your custom object from ListViewItem
then you need to construct it manually from ListViewItem
:
ListViewItem item = (MyObject)MyListView.SelectedItems[0];
MyObject foo = new MyObject();
foo.FirstName = item.Text;
foo.LastName = item.SubItems[1].Text;
foo.Age = Int32.Parse(item.SubItems[2].Text);
OR you can store custom object in Tag
property of ListViewItem
and get it back:
ListViewItem item = (MyObject)MyListView.SelectedItems[0];
MyObject foo = (MyObject)item.Tag;
BTW consider to use DataGridView
which supports binding.
Assuming your ListItems are objects of your custom class MyObject
Now in the latest Xamarin, you can do it by getting SelectedItem
and cast it to your object type.
public class ItemSelectionDemo
{
public void ItemSelected(object sender, EventArgs e)
{
MyObject item = (MyObject)MyListView.SelectedItem;
Debug.WriteLine("Selected item Id: " + item.id);
Debug.Writeline("Selected item Name: " + item.name);
}
}
public class MyObject
{
public int id;
public string name;
}
You can also use SelectedItemChangedEventArgs
in the method and get the selected item and the cast it to your object class type.
public void ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
MyObject item = e.SelectedItem as MyObject;
Debug.WriteLine("Selected item Id: " + item.id);
Debug.Writeline("Selected item Name: " + item.name);
}
I think you need to create your object differently, not casting in this way.
If you retrieve the text in the item, then create your object using that text.
string txt = MyListView.SelectedItems[0].Text;
MyObject foo = new MyObject(txt);
Then use your object in the usual way. It is difficult to tell any more about what you need without more details.