您可以将“ListBoxItem”(类型对象)转换为实际的类。
这里有一个小例子,如何在ListBox 中添加、读取和修改项目:
// Example class
public class RineItem
{
public string Name { get; set; }
public int Id { get; set; }
// Override ToString() for correct displaying in listbox
public override string ToString()
{
return "Name: " + this.Name;
}
}
public MainWindow()
{
InitializeComponent();
// Adding some examples to our empty box
this.ListBox1.Items.Add(new RineItem() { Name = "a", Id = 1 });
this.ListBox1.Items.Add(new RineItem() { Name = "b", Id = 2 });
this.ListBox1.Items.Add(new RineItem() { Name = "c", Id = 3 });
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Loop through SelectedItems
foreach (var item in this.ListBox1.SelectedItems)
{
// Have a look at it's type. It is our class!
Console.WriteLine("Type: " + item.GetType());
// We cast to the desired type
RineItem ri = item as RineItem;
// And we got our instance in our type and are able to work with it.
Console.WriteLine("RineItem: " + ri.Name + ", " + ri.Id);
// Let's modify it a little
ri.Name += ri.Name;
// Don't forget to Refresh the items, to see the new values on screen
this.ListBox1.Items.Refresh();
}
}
您面临的错误消息告诉您,没有隐式转换可以将 object 转换为 RineItem。
有可能的隐式转换(从 int 到 long)。你可以创造你自己的。举个例子:
public class RineItem2
{
public string Name2 { get; set; }
public int Id2 { get; set; }
public static implicit operator RineItem(RineItem2 o)
{
return new RineItem() { Id = o.Id2, Name = o.Name2 };
}
}
现在你可以这样做了:
RineItem2 r2 = new RineItem2();
RineItem r = r2;
但只有在 RineItem2 类中的每个对象都可以转换为 RineItem 时才应使用此方法。
从object 到RineItem 的演员每次都必须工作!因此,您不知道您的对象是什么类型,您不允许这样做:
object o = "bla bla";
RineItem r = (RineItem)o; // Not allowed! Will not work!