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

标签 c# wpf xaml mvvm itemssource

我希望名为 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/

相关文章:

c# - Entity Framework Core 3.1 - 有关命令和事务的日志信息

c# - WPF:如何在 MVVM 中播放 Storyboard?

WPF XAML 绑定(bind)和 CurrentCulture 显示

c# - 如何在wpf mvvmlight中为datagrid实现 "nextpage"函数

wpf - TargetType ="{x:Type Button}"和 TargetType ="Button"有什么区别?

WPF:XAML 属性声明不是通过 Setter 设置的?

c# - 更改属性时遇到问题

c# - 在 C# 中跨继承边界重载?

c# - 如何从 DateTime 和 TimeSpan 类型创建 DateTime 对象?

xaml - 为 Metro 应用程序的 Bing map 上的标记图钉设置动画