列表框不显示特定对象的值(数据绑定)

时间:2013-12-17 19:10:20

标签: c# wpf xaml mvvm itemssource

我希望名为LstbClients的ListBox在每个Label或TextBlock中显示Name和Phonenumber(这对我来说无关紧要),我之前使用ComboBox进行DataBinded并且运行良好,但由于某种原因它不能用于此列表框。

这是XAML代码。

<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>

这是背后的代码:

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

这是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;
    }
}

由于一些奇怪的原因,ListBox的标签只显示“,”并忽略了Name和Phonenumber,当我用我的最终WPF应用程序“打开”ListBox时,所有数据都包含......所以ListBox获取数据,但它只是不想在lstbClients的标签上显示它,所以我无法识别哪个标签包含哪些数据。

1 个答案:

答案 0 :(得分:3)

  

绑定适用于属性,而不适用于字段。

将您的字段更改为以下属性:

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

在旁注中,您应该为您的班级实施INotifyPropertyChanged,以防您希望在任何属性更改时刷新GUI。请参阅此参考 - How to implement Property change notification