Reputation: 4490
I have a ListBox in my App. Also I have a collection of the items and each of this items have the collection of the items inside. So, actually it's a tree and I want to display them like folders/files.
class item
{
...
List<item> childItems;
}
There are different types of items, some of them is not folders or files and I do not want to display them (all of them have the same base type).
So, I'm new in c#, but I feel that there should be the way to filter the items at runtime. Maybe when ListBox is trying to get the items from the List and fill itself, because I heard a little about the enumerable arrays in c#.
In c++ I fill the ListCtrl manually, but in c# there is a binding and it's cool. Currently I copy the items to ObservableCollection, filter the unwanted items and then use this collection as itemsSouce with ListBox. Maybe there is another way to filter items at runtime? I think that I should deliver my own List from the c# List and do something with enumerable interface, yep?
Upvotes: 1
Views: 484
Reputation: 4636
I'm not sure what exactly your filtering logic looks like but you could create a filtered property that you bind to like this...
class item
{
...
List<item> childItems;
public IEnumerable<item> FileSystemItems
{
get
{
return childItems.Where(x => x is IFile || x is IFolder);
}
}
}
EDIT: WP7.1 doesn't have IEnumerable.Where
I've hand edited this and can't compile it so bear with me... but wihtout using .Where it could look something like this...
public List<item> FileSystemItems
{
get
{
var list = new List<item>();
foreach (child in childItems)
{
if (child is IFile || child is IFolder)
list.Add(child);
}
return list;
}
}
Obviously replace IFile and IFolder with whatever your actual filter strategy looks like.
Your listbox binding will look something like this... (this is WPF but as far as I know silverlight is the same)
<ListBox ItemsSource="{Binding FileSystemItems}">
My full WPF binding looks like this..
<ListBox ItemsSource="{Binding FileSystemItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You'll need to replace the... {Binding Name}
part... replace Name
with whatever property you want to display in your listbox... or you can leave that off if you aren't using an ItemTemplate.
Upvotes: 2