wpf 将对象转换为 List<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15272818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:56:22  来源:igfitidea点击:

Converting Object to List<String>

c#.netwpf

提问by Simsons

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

我从 WPF Attached Behavioral for ListBox 获取所选项目列表,如下所示:

  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.

虽然它有效,但有没有其他更好的方法。

回答by Kendall Frey

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

SelectedItems属性是IList,所以我假设您的对象也是。

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();

回答by Grant Thomas

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.

然后你有一个适当的项目集合。