Question

I want the ListBox called LstbClients to show Name and Phonenumber in each Label or TextBlock (it does not matter to me), I have DataBinded before with a ComboBox and that worked pretty well, but for some reason it's not working for this ListBox.

This is the XAML code.

<ListBox x:Name="lstbClients"
         Height="300"
         Grid.Row="0" Grid.Column="0"
         Style="{StaticResource inputControls}"
         ItemsSource="{Binding clients}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding Name}"/>
                <Label Content=", "/>
                <Label Content="{Binding Phonenumber}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This is the code behind:

//clients is a filled ObservableCollection<client>
lstbClients.ItemsSource = clients;

This is the code behind Client.cs

public class Client
{
    public int ID;
    public string Lastname;
    public string Name;
    public string Streetname;
    public string Postcode;
    public string City;
    public int Phonenumber;
    public string Email;
    public DateTime CreationDate;
    public DateTime BirthDate;

    public Client(int id, string lastname, string name, DateTime birthDate, string streetname, string postcode, string city, int phonenumber, string email, DateTime creationDate)
    {
        this.ID = id;
        this.Lastname = lastname;
        this.Name = name;
        this.Streetname = streetname;
        this.Postcode = postcode;
        this.City = city;
        this.Phonenumber = phonenumber;
        this.Email = email;
        this.CreationDate = creationDate;
        this.BirthDate = birthDate;
    }
}

For some odd reason the Labels of the ListBox does only show the "," and ignores the Name and Phonenumber, and yes when I "open" ListBox with my final WPF application, all the data does contain... So the ListBox get's the Data but it just doesn't want to display it on the label of the lstbClients, so I cannot identify which label contain what data.

Was it helpful?

Solution

Binding works with properties and not with fields.

Change your fields to properties like this:

public string Name {get; set;}
public int Phonenumber {get; set;}

On a sidenote you should implement INotifyPropertyChanged for your class in case you want GUI to be refresh on any property change. Refer to this for reference - How to implement Property change notification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top