基本上,我有4个文件正在处理:
DBDisplay.xaml
DBDisplay.xaml.cs
DBDisplayViewModel.cs
DBConn.cs
在我的ViewModel中,我试图从我的.xaml文件填充以下DataGrid:
<DataGrid ItemsSource="{Binding Path=Users}"/>
使用以下代码:
public class DBDisplayViewModel
{
public ICollectionView Users { get; set; }
DBConn dbCon; // the connection object
DataSet dataSet;
DataRow dataRow;
private void Load()
{
string connectionString = Properties.Settings.Default.UserDB;
dbCon = new DBConn(connectionString);
dbCon.openConnection();
dataSet = dbCon.getDataSet(Queries.SelectAll);
DataTable table = dataSet.Tables[0];
PopulateTextFields(table, 1);
//Something to go here to populate the DataGrid
}
private void PopulateTextFields(DataTable table, int i)
{
dataRow = table.Rows[i];
}
public DBDisplayViewModel()
{
Load();
Users = CollectionViewSource.GetDefaultView(SOMETHING_HERE);
}
private void Closed(object sender, EventArgs e)
{
dbCon.closeConnection();
}
}
所以SOMETHING_HERE
应该链接到我的数据库(因为这是我之前连接到用户列表的方式)
我也认为我需要像
DataGrid.DataSource = table; //DataGrid would be linking to the xaml code
填充DataGrid
我在这里结束,所以如果有人可以提供帮助,我会非常高兴!
答案 0 :(得分:2)
由于您是WPF的新手,所以我会保持简单。要显示记录列表,您需要一个集合。您可以使用以下内容获取此代码:
Users = CollectionViewSource.GetDefaultView(dataset1.Tables[0].DefaultView);
答案 1 :(得分:1)
我担心你不会采用MVVM方式。我会用简单的语言解释一下。理想情况下,您应该有一个模型类,并且您的数据访问代码应返回此类对象的集合。更重要的是,您的视图模型有多个不应该履行的职责(从SOLID原则中读取S)。它应该负责更改UI状态和/或在View上显示数据。应该有一个单独的类,它将数据从数据库提取到ViewModel。
DBDisplay.xaml.cs
public DBDisplay()
{
InitializeComponent();
var viewModel = new DBDisplayViewModel();
viewModel.UserRepository = new UserRepository(); // You could use dependency injection but I left for simplicity.
this.DataContext = viewModel;
}
DBDisplayViewModel.cs
public class DBDisplayViewModel
{
private ObservableCollection<User> users;
public DBDisplayViewModel() {
Load();
}
public IUserRepository UserRepository
{
get; set;
}
public ObservableCollection<User> Users
{
get {
if(users == null) {
users = new ObservableCollection<User>();
}
return users;
}
set {
if(value != null) {
users = value;
}
}
}
private void Load() {
List<User> users = UserRepository.GetUsers();
Users = new ObservableCollection<User>(users);
}
}
IUserRepository.cs
public interface IUserRepository
{
List<User> GetUsers();
}
UserRepository.cs
public class UserRepository : IUserRepository
{
public List<User> GetUsers() {
List<User> users;
// put your data access code here
// and transform list of user model using dataset or SQL data reader.
return users;
}
}
User.cs(这是模型)
public class User
{
// some properties
}