Listbox不能显示特定对象的值(数据绑定)

4
我希望可以在名为LstbClients的ListBox中,每个Label或TextBlock中显示名称和电话号码(对我来说并不重要)。我以前使用ComboBox进行了数据绑定,效果很好,但由于某些原因,这个ListBox无法工作。
以下是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的标签只显示“,”,而忽略了名称和电话号码,当我用最终的WPF应用程序“打开”ListBox时,所有数据都包含在内... 所以ListBox获取了数据,但它只是不想在lstbClients的标签上显示它,所以我无法识别哪个标签包含哪些数据。


展示客户端类的代码。为什么要从XAML和后台代码中设置ItemsSource? - Rohit Vats
5
欢迎来到这个网站!在你的问题中不需要加上“对不起,我是初学者”的话语 - 每个人都曾经是一个初学者,所以不用担心。祝你的项目好运! - Sergey Kalinichenko
你的 XAML 看起来很好,我猜你在 Observable Collection 上没有实现 INotifyPropertyChanged。请展示 Observable Collection 声明的代码。同时,在运行时检查输出窗口以确保你没有出现绑定错误,这些错误可以帮助你找到问题所在。 - Daryl Behrens
我确实没有INotifyPropertyChanged...这不是MVVM的一部分吗? - Kil'jaeden
1个回答

3

绑定工作是与属性而非字段一起使用的。

将您的字段更改为如下所示的属性:

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

顺便提一下,你应该为你的类实现INotifyPropertyChanged,以便在任何属性更改时刷新GUI。请参考如何实现属性更改通知


谢谢!这个有效,我一直以为当你不在内部实现逻辑时get和set是不必要的...但看起来我错了。无论如何,感谢这个答案,我还会更多地了解INotifyPropertyChanged。 - Kil'jaeden
这些是自动属性。编译器会在幕后自动为您创建备份字段。 - Rohit Vats

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接