我试图在 WPF 中做一个地址簿。如何将我的联系人数据绑定到列表框?这是我的联系课程:
public class Contact
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string familyname;
public string FamilyName
{
get { return familyname; }
set { familyname = value; }
}
private string phonenumber;
public string PhoneNumber
{
get { return phonenumber; }
set { phonenumber = value; }
}
}
这个我的 Xaml:我有 3 个用于姓名、家庭姓名和电话号码的文本框;用于创建新联系人的列表框和按钮
<Window x:Class="PhoneBookTest10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AddressBook" Height="350" Width="525" FontStyle="Italic">
<Grid>
<ListBox Height="188" HorizontalAlignment="Left" Margin="25,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="197" />
<Label Content="Name" Height="28" HorizontalAlignment="Left" Margin="259,64,0,0" Name="label1" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,69,28,0" Name="textBox1" VerticalAlignment="Top" Width="120" DataContext="{Binding}" />
<Label Content="FamilyName" Height="28" HorizontalAlignment="Left" Margin="259,121,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox DataContext="{Binding}" Height="23" HorizontalAlignment="Right" Margin="0,126,28,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
<Label Content="PhoneNumber" Height="28" HorizontalAlignment="Left" Margin="259,188,0,0" Name="label3" VerticalAlignment="Top" />
<TextBox DataContext="{Binding}" Height="23" HorizontalAlignment="Right" Margin="0,193,28,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
<Button Content="Create New Contact" Height="32" HorizontalAlignment="Left" Margin="25,226,0,0" Name="button1" VerticalAlignment="Top" Width="197" />
</Grid>
</Window>
这是我的主窗口:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
contacts.Add(new Contact()
{
Name = "James",
FamilyName = "mangol",
PhoneNumber = "01234 111111"
});
contacts.Add(new Contact()
{
Name = "Bob",
FamilyName = "angol",
PhoneNumber = "01234 222222"
});
contacts.Add(new Contact()
{
Name = "Emma",
FamilyName = "pangol",
PhoneNumber = "01234 333333"
});
}
protected List<Contact> contacts = new List<Contact>();
public List<Contact> Contacts
{
get{return contacts;}
set{ contacts = value;}
}
}