我正在WPF中创建一个 AddressBook 程序,我想从一个包含联系人信息的文本文件中绑定我的DataGridColumn
。
但是,我不知道该怎么做
这是我的ViewModel(ContactsViewModel.cs):
using Caliburn.Micro;
using System.Windows;
namespace AddressBook {
public class ContactsViewModel : Screen {
//What to do here ?
}
}
这是XAML代码(ContactsView.xaml):
<UserControl x:Class="AddressBook.ContactsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataGrid FontSize="16" CanUserResizeColumns="False" SelectedIndex="1">
<DataGrid.Columns>
<DataGridTextColumn FontSize="14" Header="Name" Width="150"/>
<DataGridTextColumn FontSize="14" Header="Mobile No." Width="170"/>
<DataGridTextColumn FontSize="14" Header="Email" Width="200"/>
<DataGridTextColumn FontSize="14" Header="Address" Width="240"/>
</DataGrid.Columns>
</DataGrid>
</UserControl>
这是我的文本文件(Contacts.txt):
Humayun 032121352643 nexgenking@gmail.com A-312 korangi karachi,
Jahangir 03212515332 mawahid02@gmailcom A-584 korangi karachi
pakistan,
答案 0 :(得分:0)
您需要ViewModel中的集合属性,并为控件名称属性指定相同的名称。请参阅以下代码。
<DataGrid FontSize="16" x:Name="List" AutoGenerateColumns="False" CanUserResizeColumns="False" SelectedIndex="1">
<DataGrid.Columns>
<DataGridTextColumn FontSize="14" Header="Name" Width="150" Binding="{Binding Name}"/>
<DataGridTextColumn FontSize="14" Header="Mobile No." Width="170" Binding="{Binding MobileNo}"/>
<DataGridTextColumn FontSize="14" Header="Email" Width="200" Binding="{Binding Email}"/>
<DataGridTextColumn FontSize="14" Header="Address" Width="240" Binding="{Binding Address}"/>
</DataGrid.Columns>
</DataGrid>
public class ContactsViewModel : Screen
{
public ContactsViewModel()
{
string str = File.ReadAllText("Contacts.txt");
string[] strContracts = str.Split(',');
foreach (var item in strContracts)
{
string[] fields = item.Trim().Split(' ');
_list.Add(new Contact() { Name = fields[0],MobileNo= fields[1],Email=fields[2],Address=fields[3] });
}
}
private IObservableCollection<Contact> _list = new BindableCollection<Contact>();
public IObservableCollection<Contact> List
{
get { return _list; }
set
{
_list = value;
NotifyOfPropertyChange(() => List);
}
}
}
public class Contact
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
private string mobileNo;
public string MobileNo
{
get { return mobileNo; }
set { mobileNo = value; }
}
}
在此示例中,List是集合的Property属性以及Datagrid的名称。在viewmodel的构造函数中有文件数据的解析逻辑并从中创建一个集合对象