【问题标题】:Listbox does not display values of a specific object (Databinding)列表框不显示特定对象的值(数据绑定)
【发布时间】:2013-12-17 19:10:19
【问题描述】:

我希望名为 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 的标签只显示“,”并忽略名称和电话号码,是的,当我用我的最终 WPF 应用程序“打开”ListBox 时,所有数据确实包含......所以ListBox 获取的是数据,但它只是不想在 lstbClients 的标签上显示它,所以我无法识别哪个标签包含哪些数据。

【问题讨论】:

  • 显示客户端类的代码。为什么要从 XAML 和背后的代码设置 ItemsSource?
  • 欢迎来到本站!没有必要在你的问题中加上“对不起,我是初学者”——每个人都是初学者,所以不用担心。祝你的项目好运!
  • 您的 XAML 看起来不错,我猜您尚未在 Observable 集合上实现 INotifyPropertyChanged。请显示 Observable Collection 的声明代码。此外,在运行时检查您的输出窗口,以确保您没有收到绑定错误。这些可以帮助您找到问题。
  • 我确实没有 INotifyPropertyChanged... 这不是 MVVM 的东西吗?

标签: c# wpf xaml mvvm itemssource


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢!这行得通,我总是认为当你不将逻辑放入其中时,get 和 set 是不必要的......但看起来我错了。无论如何,感谢这个答案,我也会更多地了解 INotifyPropertyChanged
  • 这些是自动属性。编译器会在后台自动为您创建备份字段。
猜你喜欢
  • 1970-01-01
  • 2020-11-14
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 2011-11-27
  • 2012-11-12
相关资源
最近更新 更多