简体   繁体   中英

WPF Listbox Items

I have a ListBox control that contains the names of files inside a directory.

How would I iterate though the controls and get those names? I've tried:

for (int i = 0; i < listboxFileGroups.Items.Count; i++)
{
    // I don't want to use properties that start with Selected           
    // Here is what I was looking for
    string textItem = listboxFileGroups.Items[i].ToString();
}

Any suggestions?

You may want to explore an MVVM approach.

In one of your view model classes, you can have an ObservableCollection<string> :

public ObservableCollection<string> StuffForListBox { get; set; }

Populate that ObservableCollection with what you want to get displayed in the ListBox. In the code-behind of the UserControl or Window in which you have the ListBox, set the DataContext to an instance of the class containing StuffForListBox seen above.

this.DataContext = new MyClass();

Alternatively you could also create a datatemplate for the usercontrol / window which will automagically wire up the datacontext with your view model.

Since you only mentioned that you want to display the files in a directory (not including sub-directories), you just need to bind the ItemsSource to StuffForListBox.

   <ListBox ItemsSource="{Binding StuffForListBox}" ... >

To iterate through the strings displayed in the ListBox you just need to iterate through the ObservableCollection.


If you don't want to bother with MVVM or if that is some third party listbox, you can try grabbing the ItemsSource in the codebehind and loop through that but I'd certainly recommend MVVM. It'll make your life easier.


Now, if you wanted to get a little crazier and display things like subfolders then an ObservableCollection<string> won't cut it. You would need to create a class that contains children to model how a folder has files and subfolders.

 public class DemoItem
 {
    public string Name { get; set; }
    public DemoItem Parent { get; set; }
    public ObservableCollection<DemoItem> Children { get; set; }
    public bool IsSelected { get; set; }
 }

...and then base your observable collection thats bound to the listbox on the above class.

If and when you do that, your listbox won't display the items properly until you create a DataTemplate But I suppose that't outside of the scope of the question :p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM