我有一个绑定到可观察对象集合的数据网格。我想要做的是有一个按钮,它将执行一个对象的方法,表示被点击的按钮行。所以我现在拥有的是这样的:
<DataGridTemplateColumn Header="Command">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="cmdCommand" Click="{Binding Command}"
Content="Command"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
哪个不起作用并报告以下错误:
Click =“{Binding Command}”无效。 '{Binding Command}'不是有效的事件处理程序方法名称。只有生成的或代码隐藏类的实例方法才有效。
我看过命令绑定,但看起来它最终会转到单个外部命令而不是绑定到行的对象。我让它在后面的代码上使用事件处理程序,然后将其路由到绑定到所选行的项目(因为在单击按钮时行被选中)但这似乎是处理这个的糟糕方式我假设我'我在这里遗漏了一些东西。
答案 0 :(得分:84)
我一直这样做。以下是一个示例以及如何实现它。
更改您的XAML以使用按钮的Command属性而不是Click事件。我使用名称SaveCommand,因为它更容易遵循名为Command。
的东西<Button Command="{Binding Path=SaveCommand}" />
Button现在绑定的CustomClass需要具有类型为ICommand
的名为SaveCommand的属性。它需要指向要在执行命令时运行的CustomClass上的方法。
public MyCustomClass
{
private ICommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(
param => this.SaveObject(),
param => this.CanSave()
);
}
return _saveCommand;
}
}
private bool CanSave()
{
// Verify command can be executed here
}
private void SaveObject()
{
// Save command execution logic
}
}
上面的代码使用了一个RelayCommand,它接受两个参数:要执行的方法,以及命令可以执行的真/假值。 RelayCommand类是一个单独的.cs文件,代码如下所示。我是从Josh Smith那里得到的:)
/// <summary>
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> 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<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
答案 1 :(得分:25)
你有各种各样的可能性。最简单和最丑陋的是:
<强> XAML 强>
<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/>
代码背后
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((YourClass)fe.DataContext).DoYourCommand();
}
另一个解决方案(更好)是在YourClass
上提供ICommand属性。此命令已经引用了您的YourClass
- 对象,因此可以对此类执行操作。
<强> XAML 强>
<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>
因为在写这个答案时,发布了很多其他答案,我停止写更多。如果您对我展示的某种方式感兴趣,或者如果您认为我犯了错误,请发表评论。
答案 2 :(得分:7)
以上是Rachel上面回答的VB.Net演绎。
显然XAML绑定是一样的......
<Button Command="{Binding Path=SaveCommand}" />
您的自定义类看起来像这样......
''' <summary>
''' Retrieves an new or existing RelayCommand.
''' </summary>
''' <returns>[RelayCommand]</returns>
Public ReadOnly Property SaveCommand() As ICommand
Get
If _saveCommand Is Nothing Then
_saveCommand = New RelayCommand(Function(param) SaveObject(), Function(param) CanSave())
End If
Return _saveCommand
End Get
End Property
Private _saveCommand As ICommand
''' <summary>
''' Returns Boolean flag indicating if command can be executed.
''' </summary>
''' <returns>[Boolean]</returns>
Private Function CanSave() As Boolean
' Verify command can be executed here.
Return True
End Function
''' <summary>
''' Code to be run when the command is executed.
''' </summary>
''' <remarks>Converted to a Function in VB.net to avoid the "Expression does not produce a value" error.</remarks>
''' <returns>[Nothing]</returns>
Private Function SaveObject()
' Save command execution logic.
Return Nothing
End Function
最后RelayCommand类如下......
Public Class RelayCommand : Implements ICommand
ReadOnly _execute As Action(Of Object)
ReadOnly _canExecute As Predicate(Of Object)
Private Event ICommand_CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
''' <summary>
''' Creates a new command that can always execute.
''' </summary>
''' <param name="execute">The execution logic.</param>
Public Sub New(execute As Action(Of Object))
Me.New(execute, Nothing)
End Sub
''' <summary>
''' Creates a new command.
''' </summary>
''' <param name="execute">The execution logic.</param>
''' <param name="canExecute">The execution status logic.</param>
Public Sub New(execute As Action(Of Object), canExecute As Predicate(Of Object))
If execute Is Nothing Then
Throw New ArgumentNullException("execute")
End If
_execute = execute
_canExecute = canExecute
End Sub
<DebuggerStepThrough>
Public Function CanExecute(parameters As Object) As Boolean Implements ICommand.CanExecute
Return If(_canExecute Is Nothing, True, _canExecute(parameters))
End Function
Public Custom Event CanExecuteChanged As EventHandler
AddHandler(ByVal value As EventHandler)
AddHandler CommandManager.RequerySuggested, value
End AddHandler
RemoveHandler(ByVal value As EventHandler)
RemoveHandler CommandManager.RequerySuggested, value
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
If (_canExecute IsNot Nothing) Then
_canExecute.Invoke(sender)
End If
End RaiseEvent
End Event
Public Sub Execute(parameters As Object) Implements ICommand.Execute
_execute(parameters)
End Sub
End Class
希望能帮助任何VB.Net开发人员!
答案 3 :(得分:1)
点击是一个事件。在您的代码中,您需要为XAML中的任何内容提供相应的事件处理程序。在这种情况下,您需要具备以下条件:
private void Command(object sender, RoutedEventArgs e)
{
}
命令不同。如果您需要连接一个命令,那么您将使用该按钮的Commmand属性,您可以使用一些预构建的命令,也可以通过CommandManager类连接自己的命令(我认为)。
答案 4 :(得分:0)
Rachel已经给出了解决方案的更多解释:
&#34;使用Model-View-ViewModel设计模式的WPF应用&#34;
乔什史密斯答案 5 :(得分:0)
在 Xamarin Forms 上,最丑陋和最直接的版本:
XML:
<Button Margin="0,10,0,0"
Text="Access galery"
Clicked="OpenGalery"
BackgroundColor="{StaticResource Primary}"
TextColor="White" />
然后:在.cs
private async void OpenGalery(object sender, EventArgs e)
{
//do your bidding
}