簡體   English   中英

如何將ListBox.Items用作列表的Itemsource <String>

[英]How to use ListBox.Items as Itemsource of a List<String>

我有一個ListBox 我在后面的代碼中也有一個list 我想從所有項目listbox作為我的源list

我這樣嘗試:

<listBox x:Name="MyList" .../>

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

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

但是它拋出一個異常: System.InvalidCastException

該怎么辦?

因為列表不是由字符串組成的,所以出現錯誤! 嘗試獲取字符串表示形式。

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

這是正確的方法。 但是,請查看列表框中具有的項目類型。 它們可能不是string類型,這就是為什么您會收到此錯誤。 您可能沒有類型為string項目。 在您的ListBox中用該類型替換T。 或修復您的ListBox以使項目具有string類型。

我認為山姆的答案是正確的。 如果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。

您知道在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()); } List<string> list = new List<string>(); foreach (var item in this.MyList.Items) { ListBoxItem castItem = item as ListBoxItem; list.Add(castItem.Content.ToString()); }

在這里你可以嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM