好吧,我一直在关注的教程都是基于 c# 的 winforms 端,而我的应用程序是基于 wpf 的。然而,尽管我的应用程序运行良好,但有人告诉我有一种使用 MVVM 绑定(bind)文本框的更好方法。然而,我一直很难找到与基于 wpf 的教程相关的 MySQL,这些教程涵盖了 MVVM 数据绑定(bind)。
这是我目前的做事方式,到目前为止它是有效的。显然它可能会更好......
string sqlcon = "datasource = localhost; port = 3306; username = root; password = root";
string query = "Select * from users.login where tag = '" + this.tag.Text + "' ;";
new MySqlConnection(sqlcon);
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader rdr;
try
{
con.Open();
rdr = cmd.ExecuteReader();
MessageBox.Show("Saved");
while (rdr.Read())
{
//Declarations
string susername = GetString(rdr, "username");
string spassword = GetString(rdr, "password");
string ssecurity = GetString(rdr, "question");
string sanswer = GetString(rdr, "answer");
//Binding strings to textboxes
username.Text = susername;
password.Text = spassword;
question.Text = ssecurity;
answer.Text = sanswer;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
也许我没有在正确的地方寻找,但我找不到任何与 xaml 有任何关系的 MySQL 数据绑定(bind)的特定内容。在 wpf 中执行此操作的最佳方法是什么?即使只是一个例子也可以。这样我至少可以得到一个想法。
最佳答案
更简单的方法是使用实体框架:
http://msdn.microsoft.com/en-us/data/ef.aspx
MVVM Entity Framework 啧啧
http://msdn.microsoft.com/en-us/data/jj574514.aspx
如果你真的想使用它,请先尝试了解它。
我一开始是按照你的方式做的,但现在我用了这个,我发现它更容易。
此外,当使用 MVVM 时,您只需为 Entity Framework 对象创建一个项目,然后链接到您的模块。
如果你想像现在那样做,你可以这样做:
一些图:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
http://www.codeproject.com/Articles/124160/Using-WPF-MVVM-for-Database-Access
查看
将项目源添加到您的对象,
ItemsSource="{Binding}"
并尝试从加载到那里的数据库中获取内容,这已经是一大步了。
关于c# - 如何在wpf中将文本框绑定(bind)到MySQL数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22009783/