[Solved] binding an List of objects to a Listbox


The Error you are getting is probably:

Items collection must be empty before using ItemsSource.

There is probably no problem with binding…. your bigest problem is invalid xaml.

I am not sure what you are trying to achieve, but I guess you want to have listbox with horizonatal Stackpanel as ItemsPanel.

Then it should be like this:

<ListBox ... >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
             <StackPanel Orientation="Horizontal" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

And then you probably want to provide an ItemTemplate

<ListBox ... >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
             <StackPanel Orientation="Horizontal" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
   <ListBox.ItemTemplate>
       <DataTemplate>
           <Border Background="Red" Width="150" Height="100">
               <TextBlock Text="{Binding Path=programName}" />
           </Border>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

EDIT

After you edited your question it seems that you have new problem. Still… your XAML should not be working. If you used one you provided with your question. It’s invalid.

If you are getting result like:

Namespace.FileInfo
Namespace.FileInfo
Namespace.FileInfo
Namespace.FileInfo

then your binding in ItemTemplate is not working correctly. Make sure programName is public property.

The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.

As I said. My code works fine.

UPDATE

List<FileInfo> should be ListBox‘s DataContext… it probably is… since you get this result. What you should check is that in FileInfo class is programName as public property.

It should be something like this.

public class FileInfo : ObservableObject
{
  private string _programName;

  public string programName
  {
      get{ return this._programName;}
      set
      {
          this._programName = value;
          RaisePropertyChanged(() => this.programName);
      }
   }
}

5

solved binding an List of objects to a Listbox