【发布时间】:2021-08-16 17:45:55
【问题描述】:
在 MainWindow.xaml 中,我有一个名为 tbName 的文本框。在它下面我有一个带有 OnClickEvent 的按钮。我想在另一个名为 EmployeeRank1 的窗口中设置名为 welcomeRank1Tb 的 TextBlock 的文本,并在 tbName 文本框中输入文本。如何从 MainWindow.xaml.cs 访问 welcomeRank1Tb 并将其值设置为 tbName 中输入的值?
private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
{
// creat SqlConnection, SqlCommand and SqlDataReader instances
SqlConnection con;
SqlCommand cmd;
SqlDataReader reader;
// try-catch block that looks for match between input and database information for EmployeeRank1
try
{
string connectionString = ConfigurationManager.ConnectionStrings["CompanyManagementSystemm.Properties.Settings.ZaimovDBConnectionString"].ConnectionString;
// create a query and select just the record we need
string query = "select * from EmployeeRank1 where Name = @name AND Password = @pass";
// A local sqlconnection in a using statement ensure proper disposal at the end of this code
con = new SqlConnection(connectionString);
con.Open();
// Let the database do the work to search for the password and name pair
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = tbName.Text;
cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = pbPassword.Password;
reader = cmd.ExecuteReader();
// If the reader has rows then the user/pass exists in the db table
if (reader.HasRows)
{
EmployeeRank1 employeeRank1 = new EmployeeRank1();
employeeRank1.Show();
}
else
{
NamePassNotMatchFrame.Content = new NamePassNotMatch();
}
}
// catch a potential exception
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
我想更改if (reader.HasRows) 语句中welcomeRank1Tb 的值
【问题讨论】:
-
这不是一个直接的答案,但我建议使用绑定并在各个视图模型之间进行这样的操作。从另一个窗口修改一个窗口听起来像是代码异味。
-
创建窗口后立即设置?:
employeeRank1.welcomeRank1Tb.Text = tbName.Text -
@mm8 确实有效。我不知道为什么我什至不认为它是一种选择,即使它是合乎逻辑的。谢谢!