所以我编写了一个简单的数据绑定练习项目,但我有一点问题。我有一个ObservableCollection,我数据绑定到ListBox。当我运行程序时,似乎一开始ListBox中没有任何东西,但是当我将鼠标悬停在它上面时,我可以看到与ObservableCollections完全相同数量的项目的轮廓,但没有任何内容。 这是我的代码:
XAML:
<ListBox Margin="0, 40, 0, 0" x:Name="lb1" ScrollViewer.CanContentScroll="True">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBlock DockPanel.Dock="Left" x:Name="_age" Text="{Binding Path=Age}"/>
<TextBlock DockPanel.Dock="Right" x:Name="_cash" Text="{Binding Path=Cash}" />
<TextBlock DockPanel.Dock="Top" x:Name="_name" Text="{Binding Path=FullName}"/>
<TextBlock DockPanel.Dock="Top" x:Name="_gender" Text="{Binding Path=Gender}"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码隐藏:
public class Person{
public Person(string _FullName, int _Age, string _Gender, string _AboutMe, decimal _Cash)
{
this.FullName = _FullName;
this.Age = _Age;
this.Gender = _Gender;
this.AboutMe = _AboutMe;
this.Cash = _Cash;
}
public string FullName;
public int Age;
public string Gender;
public string AboutMe;
public decimal Cash;
}
public partial class MainWindow : Window
{
public ObservableCollection<Person>People = new ObservableCollection<Person>();
public MainWindow()
{
People.Add(new Person("John Doe", 35, "M", "My name is John Doe", 1500));
People.Add(new Person("Sarah Maine", 28, "F", "My name is Sarah Maine", 2150));
People.Add(new Person("George Smith", 65, "M", "My name is George Smith", 4999));
People.Add(new Person("Rachel Ramsey", 46, "F", "My name is Rachel Ramsey", 3199));
People.Add(new Person("Rachel Ramsey", 46, "F", "My name is Rachel Ramsey", 3199));
InitializeComponent();
lb1.ItemsSource = People;
}
}
有什么想法吗?感谢
答案 0 :(得分:1)
您的Person-Class需要一些属性而不仅仅是字段:
public class Person {
public Person(string _FullName, int _Age, string _Gender, string _AboutMe, decimal _Cash) {
this.FullName = _FullName;
this.Age = _Age;
this.Gender = _Gender;
this.AboutMe = _AboutMe;
this.Cash = _Cash;
}
private string fullName;
private int age;
private string gender;
private string aboutMe;
private decimal cash;
public string FullName {
get {
return fullName;
}
set {
this.fullName = value;
}
}
public int Age {
get {
return age;
}
set {
this.age = value;
}
}
public string Gender {
get {
return gender;
}
set {
this.gender = value;
}
}
public string AboutMe {
get {
return aboutMe;
}
set {
this.aboutMe = value;
}
}
public decimal Cash {
get {
return cash;
}
set {
this.cash = value;
}
}
}
考虑实施INotifyPropertyChanged