我想将 assignment_id 这是 myButton 的命令参数传递给 .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>
最佳答案
看起来您可能正在尝试混合使用命令处理程序和事件处理程序。如果你想使用命令,你应该首先用那里定义的命令创建一个 View 模型。然后将 xaml 中的数据上下文设置为该 View 模型。然后你应该能够按照你想要的方式绑定(bind)命令。一种常见的方法是首先定义一个 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());
}
}
}
现在您已完成设置,只需将 View 的数据上下文设置为 View 模型即可。您可以在后面的代码中或在 xaml 中执行此操作,无论您想要什么。有点像
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
现在,您在 xaml 中与命令的绑定(bind)应该如下所示:
<Button x:Name="myButton" Content="update" Command="{Binding Command}" CommandParameter="{Binding assignment_id}"></Button>
然而,当我们在这里时,请更改您的 sql 命令以使用参数,而不是像那样将其连接为字符串。以您现在的方式进行操作将使您对 sql 注入(inject)敞开大门。
编辑:需要注意的是,您绑定(bind)到 CommandParameter 的对象也应该存在于您的 View 模型中。理想情况下,您将拥有一个包含 assignment_id 属性的模型,然后您将在 View 模型中实例化该模型的一种类型,然后将该模型实例绑定(bind)到您的 View 。
关于c# - 如何传递按钮的命令参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17165032/