问题描述
我一直在尝试使用以下代码遍历WPF中列表框的选定项;
I've been trying iterate through the selected items of a listbox in WPF, with the following code;
try
{
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
ListItem li = (ListItem)mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
}
catch(Exception e)
{
// Error appears here
string error = e.ToString();
}
但是我收到无效的强制转换例外;
However I receive an invalid cast exception;
System.InvalidCastException:无法将类型为 mylist的对象强制转换为 System.Windows.Documents.ListItem。
System.InvalidCastException: Unable to cast object of type 'mylist' to type 'System.Windows.Documents.ListItem'.
是否存在
推荐答案
我发现的一种方法是将列表框分配到对象上,然后将其投射到DataRowView上。似乎可以正常工作,我可以通过它们各自的列名称访问内部的字段。
A way I found was to assign the listbox onto an object then cast this onto a DataRowView. Seems to work and I can get access to the fields inside, by their respective column names.
object selected = mylistbox.SelectedItem;
DataRow row =(((DataRowView)selected).Row;
string thecontents = row [ columnname]。ToString()。TrimEnd();
object selected = mylistbox.SelectedItem;DataRow row = ((DataRowView)selected).Row;
string thecontents = row["columnname"].ToString().TrimEnd();
这篇关于查找选定的WPF列表框条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!