1

I am getting the List of selected Items from WPF Attached Behavioral for ListBox as below:

  private void ListBoxSelectionChanged(object param)
    {
        var selectedItems = param;
        SelectedMItems = selectedItems.ToString().Split(',').ToList<string>();
        //Console.WriteLine(selectedItems.ToString());

    }

Though it works , is there any other better way.

4
  • 1
    What's the actual type? Could it be an ObservableCollection<string>? Commented Mar 7, 2013 at 13:48
  • 1
    Might be better on code review Commented Mar 7, 2013 at 13:48
  • This will work fine as long as you're confident the object correctly implements .ToString(). You haven't given any details about the object so I won't project any such confidence for you. Commented Mar 7, 2013 at 13:48
  • @GrantThomas,@jrajav, object is Collection of selected Items from ListBox , the list box has multiple selection option Commented Mar 7, 2013 at 13:49

2 Answers 2

3

The SelectedItems property is an IList, so I'm assuming your object is as well.

In this case, it would be simplest to do one of these two:

// If the list already contains strings
SelectedMItems = ((IList)selectedItems).Cast<string>().ToList();

// If the list contains other objects
SelectedMItems = ((IList)selectedItems).Cast<object>().Select(o => o.ToString()).ToList();
Sign up to request clarification or add additional context in comments.

4 Comments

Why the Cast<object>()? Everything's an object and must implement ToString() surely?
Object Does contain a method for Cast
The Cast doesn't do anything other than convert the IEnumerable to an IEnumerable<object>, because Select is not available for IEnumerable.
@Simsons I added a cast. Try again.
1

Something like this might work, in order to be 'safer':

var items = param as ObservableCollection<string>;

Or even just an enumerable:

var items = param as IEnumerable<string>;

Then you have a collection of items proper.

4 Comments

i would even go as far as doing just IEnumerable.
@Simsons Did you examine the thing in the debugger and see what it is?
Type is object {System.Windows.Controls.SelectedItemCollection}
So, do ... as SelectedItemCollection, and have a nice strongly typed thing. (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.