我希望名为 LstbClients 的 ListBox 在每个 Label 或 TextBlock 中显示名称和电话号码(这对我来说无关紧要),我之前使用 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 的标签确实只显示“,”而忽略了姓名和电话号码,是的,当我用我的最终 WPF 应用程序“打开”ListBox 时,所有数据都包含......所以ListBox 获取了数据,但它不想将其显示在 lstbClients 的标签上,因此我无法确定哪个标签包含哪些数据。
最佳答案
Binding works with properties and not with fields.
将您的字段更改为如下属性:
public string Name {get; set;}
public int Phonenumber {get; set;}
在旁注中,您应该为您的类实现 INotifyPropertyChanged
,以防您希望 GUI 在任何属性更改时刷新。引用这个引用 - How to implement Property change notification .
关于c# - 列表框不显示特定对象的值(数据绑定(bind)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642637/