通过数据库使用ViewModel填充DataGrid



基本上,我有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

我在这里,所以如果有人能帮忙,我会很高兴的!

由于您是WPF的新手,所以我将保持简单。要显示记录列表,您需要一个集合。这个集合你可以在你的代码中使用类似的东西:

Users = CollectionViewSource.GetDefaultView(dataset1.Tables[0].DefaultView);

恐怕您没有走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();
}

用户存储库.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
}

最新更新