我想将作为myButton命令参数的assignment_id传递给.cs文件来更新数据库中的值。我写了这段代码但是当我点击myButton时,它显示了一个消息框,方法和操作失败了。我该如何解决这个问题?
private void Command(Int32 parameter)
{
p = parameter;
}
private void btnUpdate_Click(Object sender, RoutedEventArgs e)
{
try
{
SqlConnection con = new SqlConnection("server=(local); Integrated Security=true; Database=nrcs");
con.Open();
SqlCommand comm = new SqlCommand("UPDATE Assignments SET assignment_title='myassignment' WHERE assignment_id=" + p + ";", con);
comm.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
这里是Xaml代码:
<Button x:Name="myButton" Content="update" Command="{Binding Command}" CommandParameter="{Binding assignment_id}" Click="btnUpdate_Click" ></Button>
答案 0 :(得分:1)
似乎您可能正在尝试混合使用命令处理程序和事件处理程序。如果要使用命令,则应首先在其中定义命令的情况下创建一个视图模型。然后在xaml中将数据上下文设置为该视图模型。然后,您应该能够以所需的方式绑定命令。一种常见的方法是首先定义一个RelayCommand类。
一个简单的中继类可能看起来像这样:
public class RelayCommand<T> : ICommand
{
#region Fields
readonly Action<T> _execute = null;
readonly Predicate<T> _canExecute = null;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="execute">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
///<summary>
///Defines the method that determines whether the command can execute in its current state.
///</summary>
///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
///<returns>
///true if this command can be executed; otherwise, false.
///</returns>
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
///<summary>
///Occurs when changes occur that affect whether or not the command should execute.
///</summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
///<summary>
///Defines the method to be called when the command is invoked.
///</summary>
///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
public void Execute(object parameter)
{
_execute((T)parameter);
}
#endregion
}
该示例来自此问题Why RelayCommand
一旦有了RelayCommand类,就可以在ViewModel中定义诸如以下的命令
public class MainWindowViewModel
{
private ICommand _Command;
public ICommand Command
{
get
{
if (_Command == null)
_Command = new RelayCommand<object>((x) => ExecuteCommand(x));
return _Command;
}
set
{
_Command = value;
}
}
private void ExecuteCommand(object parameter)
{
try
{
if (!string.IsNullOrEmpty(parameter.ToString()){
//Do sql call here. parameter.ToString() is a string representation of the parameter that was bound on the xaml
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
现在已经完成设置,只需将视图的数据上下文设置为视图模型即可。您可以根据需要在背后的代码或xaml中执行此操作。像
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
现在您在xaml中对命令的绑定应如下所示:
<Button x:Name="myButton" Content="update" Command="{Binding Command}" CommandParameter="{Binding assignment_id}"></Button>
但是,当我们在这里时,请更改您的sql命令以使用参数,而不是将其串联为这样的字符串。按现在的方式进行操作将使您可以进行sql注入。
编辑:应该注意,您绑定到CommandParameter的对象也应该存在于您的视图模型中。理想情况下,您将拥有一个包含Assignment_id属性的模型,然后在视图模型中实例化该模型的类型,然后将该模型的实例绑定到您的View。
答案 1 :(得分:0)
我认为它是调用click事件(btnUpdate_Click)和命令的顺序。如果首先调用该事件,则变量&#39; p&#39;没有值,查询将失败。
我认为你应该使用事件或命令来执行查询,而不是两者。如果您打算继续使用MVVM模式(我推荐),请在另一个类中使用该命令作为您的viewmodel。