select item from listview and cast to my custom object

后端 未结 3 1632
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 20:13

I\'m trying to select object from listview and cast to my custom object like this

MyObject foo = (MyObject)MyListView.SelectedItems[0];

but thi

相关标签:
3条回答
  • 2021-01-22 21:05

    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.

    0 讨论(0)
  • 2021-01-22 21:06

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 21:10

    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.

    0 讨论(0)
提交回复
热议问题