简体   繁体   中英

WPF ListBox with Multiple ListBoxs inside

I want to user ListBox inside ListBox in wpf, This is what I am trying to do

public ObservableCollection<Users> List1DS { get; set; }
public ObservableCollection<Users> List2DS { get; set; }
public ObservableCollection<Users> List3DS { get; set; }

public class Users
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
}
//This will have List1DS,List2DS and List3DS
public ObservableCollection<List<Users>> MainDS { get; set; }

XAML:

<ListBox Margin="25,74,835,-194" x:Name="userslst" ItemsSource="{Binding MainDS}">                      
    <ListBox ItemsSource="{Binding List1DS}">
    </ListBox>
</ListBox> 

There can be zero or multiple items in MainDS, I want to know is such thing is possible in WPF? What will be an alternate way of doing this?

Yes, this can be done by putting a listbox in the ItemTemplate of the top listbox and binding it.

But you might want to not do that and go for a treeview/hierarchical template structure as that is already what you are trying to achieve.

It is indeed possible to display a collection of collections and possibly more easily than you might imagine. You simply have to provide an ItemTemplate for the first level items that displays the second level items. Try something like this:

<ListBox ItemsSource="{Binding MainDS}">
    <ListBox.ItemTemplate>
        <DataTemplate> <!-- Define top level items -->
            <ListBox ItemsSource="{Binding}"> <!-- Bind to inner collection -->
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate>
                    <DataTemplate> <!-- Define second level items -->
                        <TextBlock Text="{Binding Name}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

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