-1

Hello I want to bind a list of custom object to a ListBox in WPF. I have the next code:

private List<User> users = new List<User>();

public MainWindow()
{
    InitializeComponent();

    this.users = User.GetAllUsersFromFile();

    this.listBox.DataContext = users;
    this.listBox.ItemsSource = users;
}

And the XML:

<ListBox x:Name="listBox" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>    
</ListBox>

And the User class:

private string name;
private byte[] avatar;

public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        if (value.Any(c => c == ' '))
            throw new Exception("Invalid name. (It cannot contain spaces)");

        this.name = value;
    }
}

public byte[] Avatar
{
    get
    {
        return this.avatar;
    }
    set
    {
        this.avatar = value;
    }
}

The initial list is showing as expected , but if new items are added to the list (or deleted) the list is not updating.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
Gabriel
  • 75
  • 2
  • 9

1 Answers1

0

As Sinatr pointed out I used ObservableCollection and it worked as expected. Thanks.

Gabriel
  • 75
  • 2
  • 9