【问题标题】:How to use ListBox.Items as Itemsource of a List<String>如何使用 ListBox.Items 作为 List<String> 的 Itemsource
【发布时间】:2014-09-10 02:34:27
【问题描述】:

我有一个ListBox。我在后面的代码中也有一个list。我想从listbox 获取所有项目作为我的list 的来源。

我试过这样:

&lt;listBox x:Name="MyList" .../&gt;

list<string> feed = new list<string>();

//to get the source
var feed = MyList.Items.Cast<string>().ToList();

但它抛出异常:System.InvalidCastException

怎么办?

【问题讨论】:

    标签: c# wpf list listbox


    【解决方案1】:

    我认为山姆的回答是正确的。如果您的 ListBox 的 ItemsSource 是字符串集合,那么将它们转换为字符串应该不是问题。

            MyList.ItemsSource = new List<string>
            {
                "one","two","three"
            };
            List<string> feed = MyList.Items.Cast<string>().ToList();
    

    但是如果你的 ListBox 的 ItemsSource 不是字符串集合,假设 MyClass 集合

        class MyClass
        {
            public string MyProperty { get; set; }
            public override string ToString()
            {
                return this.MyProperty;
            }
        }
    

    然后您必须将其转换为适当的类型并选择所需的属性。

            MyList.ItemsSource = new List<MyClass>
            {
                new MyClass {MyProperty ="one"},
                new MyClass {MyProperty ="two"},
                new MyClass {MyProperty ="three"},
            };
            List<string> feed = MyList.Items.Cast<MyClass>().Select(c => c.MyProperty).ToList();
    

    但要正确回答您的问题,我们需要了解您的 ListBox 的 ItemsSource。

    【讨论】:

      【解决方案2】:
      list<T> feed = new list<T>();
      var feed = MyList.Items.Cast<T>().ToList();
      

      这是正确的方法。但是,请查看 ListBox 中的项目类型。它们可能不是string 类型这就是您收到此错误的原因。您可能没有 string 类型的项目。将 T 替换为 ListBox 中的那种类型。或者修复您的 ListBox 以包含类型为 string 的项目。

      【讨论】:

        【解决方案3】:

        您收到错误是因为您的列表不是由字符串组成的!尝试获取字符串表示形式。

        List<string> feed = MyList.Items.Cast<object>()
            .Select(o => o.ToString()).ToList();
        

        【讨论】:

          【解决方案4】:

          你知道在 wpf 你有 Listbox 有 ListboxItem 并且你必须先将你的项目兑现到 ListboxItem。 在那之后。您将 listboxItem.Content 推送到您的 List<string> list = new List<string>(); foreach (var item in this.MyList.Items) { ListBoxItem castItem = item as ListBoxItem; list.Add(castItem.Content.ToString()); }

          你可以试试

          【讨论】:

            猜你喜欢
            • 2018-01-11
            • 2021-09-17
            • 1970-01-01
            • 2011-03-03
            • 2012-02-08
            • 1970-01-01
            • 2020-01-11
            • 2013-08-26
            • 1970-01-01
            相关资源
            最近更新 更多