我是 WPF MVVM 的新手。我有一个DataGrid
. 当我单击该DataGrid
行时,我可以访问名为员工 ID 的列值。然后我需要将所有行值绑定到相应的 TextBoxes 以进行更新。我已将命令附加到窗口的加载事件。但是在进入绑定方法时,员工 id 的值会被重置为 null。
这是我的 HomeViewModel
private DataRowView _SelectedRow;
public DataRowView SelectedRow
{
get
{
return _SelectedRow;
}
set
{
if (_SelectedRow != value)
{
_SelectedRow = value;
OnPropertyChanged("SelectedRow");
}
}
}
这是我的方法
public void bindControlValues()
{
int id=Convert.ToInt32( SelectedRow.Row["Emp_ID"]);
try
{
sqlConnection = new SqlConnection(Connection.connectionstring);
sqlConnection.Open();
selectCommand = new SqlCommand(AppConstants.StoredProcedures.GetDataProcedure);
selectCommand.CommandType = CommandType.StoredProcedure;
selectCommand.Parameters.Add(AppConstants.Parameters.Emp_ID, SqlDbType.Int).Value = id;
sqlAdapter = new SqlDataAdapter(selectCommand);
sqlDataSet = new DataSet();
sqlAdapter.Fill(sqlDataSet);
employee.FirstName = sqlDataSet.Tables[0].Rows[0][1].ToString();
employee.LastName = sqlDataSet.Tables[0].Rows[0][2].ToString();
employee.Dob = Convert.ToDateTime(sqlDataSet.Tables[0].Rows[0][3].ToString());
employee.Age = Convert.ToInt32(sqlDataSet.Tables[0].Rows[0][4].ToString());
employee.Street1 = sqlDataSet.Tables[0].Rows[0][5].ToString();
employee.Street2 = sqlDataSet.Tables[0].Rows[0][6].ToString();
employee.City = sqlDataSet.Tables[0].Rows[0][7].ToString();
employee.State = sqlDataSet.Tables[0].Rows[0][8].ToString();
employee.ZipCode = sqlDataSet.Tables[0].Rows[0][9].ToString();
employee.PhoneNumber = sqlDataSet.Tables[0].Rows[0][10].ToString();
employee.MobileNumber = sqlDataSet.Tables[0].Rows[0][11].ToString();
employee.Email = sqlDataSet.Tables[0].Rows[0][12].ToString();
employee.Web = sqlDataSet.Tables[0].Rows[0][13].ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
selectCommand.Dispose();
sqlDataSet.Dispose();
}
}
这是我的 xaml 代码
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding BindControlValueCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBox Name="txtFirstName" Text="{Binding Path=FirstName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
<TextBox Name="txtLastName" Text="{Binding Path=LastName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"></TextBox>