Home > Mobile >  ListBox Split Into Two Columns
ListBox Split Into Two Columns

Time:06-25

I would like to have my ListBox layout like this: A tabular layout with two columns, one for the title and one for the authors of books.

But currently I have this: A single column showing data.

And my xml code looks like this:

<ListBox DockPanel.Dock="Top" Grid.Column="1" Grid.Row="1" Height="200" ScrollViewer.VerticalScrollBarVisibility="Visible">
    <ListBoxItem Width="325" Content="Visual Basic"/>
    <ListBoxItem Width="325" Content="Silverlight"/>
    <ListBoxItem Width="325" Content="ASP.NET"/>
    <ListBoxItem Width="325" Content="WCF"/>
    <ListBoxItem Width="325" Content="Web Services"/>
    <ListBoxItem Width="325" Content="Windows Service"/>
</ListBox>

So how can I make two columns in a ListBox and add data to them?

CodePudding user response:

Here is an inspiration how you could display your enthusiasm for boats. This is a simple example in code-behind, as I do not know how deep your knowledge about WPF is.

First, create a data type that represents a book with a Title and an Authors property.

public class Book
{
   public Book(string title, IEnumerable<string> authors)
   {
      Title = title;
      Authors = authors;
   }

   public string Title { get; }

   public IEnumerable<string> Authors { get; }
}

Then in your window's code-behind, expose a collection for your books and initialize it in the constructor. Set the DataContext to this, so bindings will have the window as source and find the Books property.

public partial class MainWindow
{
   public MainWindow()
   {
      InitializeComponent();
      
      Books = new List<Book>
      {
         new Book("Boaty McBoatface", new[] { "Byron Barton" }),
         new Book("Boat life", new[] { "Jeremy Boats", "Bud Shipman" }),
         new Book("Boat Boys", new[] { "Will Buy Boats" }),
      };
      
      DataContext = this;
   }
   
   public IEnumerable<Book> Books { get; }
}

Now, create a ListView that binds its ItemsSource to the Books property. Remember, the binding will resolve the property on the window, as we set it as DataContext.

Add a A GridView with two columns, one for the book title and one for authors.


This is a more or less simple example to start with. You should sooner or later start learning the MVVM design pattern to improve separation of the user interface and your data and business logic. To migrate this example to MVVM, you would move the books collection property to a view model that you would set as DataContext e.g. of the window.

Further reading:

By the way, in general a ListBox does not have built-in support for columns, a ListView does through GridView. There is even a much more powerful but at the same time complex control for tabular data, the DataGrid, in case you ever need it. Keep on boating!

  • Related