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开发者_JAVA技巧)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: Unable to cast object of type 'mylist' to type 'System.Windows.Documents.ListItem'.
Is there a way around this?
I prefer to do it using data binding: Sync SelectedItems in a muliselect listbox with a collection in ViewModel
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
List**Box**Item li = (List**Box**Item)mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
This should work:
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
var li = mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
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();
You are confusing ListItem
with ListBoxItem
.
If you do nothing special, a ListBox
will create ListBoxItem
containers for the data you bind to it. ListItem
is used inside FlowDocument
and is basically a numbered or bulleted point in a document.
That said, data binding would be better. If you were using data binding, SelectedItems would not be a ListBoxItem but would be your actual data item that was bound. You can cast this to the appropriate type and use it.
The listbox adds it's items as a collection of objects, so it can't cast it to ListItem. So for your purpose , you can do as following :
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
string listitemcontents_str = mylistbox.SelectedItems[i].ToString();
}
If you really want to use ListBoxItem , please add these items to your listbox e.g.
ListBoxItem li = new ListBoxItem();
li.Content = "Hello";
mylistbox.Items.Add(li);
then you can do what you want without Invalid cast exception:
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
ListBoxItem li = (ListBoxItem)mylistbox.SelectedItems[i];
string s = li.ToString();
}
精彩评论