我不知道您的 RelayCommand 类是什么样的,但我让您使用这些类架构来工作。
中继命令类:
#region Referenceing
using System;
using System.Diagnostics;
using System.Windows.Input;
#endregion
public class RelayCommand : ICommand
{
#region Fields
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute) : this(execute, null)
{
}
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 parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
XAML:
<Window x:Class="StackTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:this="clr-namespace:StackTest"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<this:ViewModel/>
</Window.DataContext>
<Grid>
<TextBlock>
<Hyperlink Command="{Binding TestCommand}" CommandParameter="Tester">
Test
</Hyperlink>
</TextBlock>
</Grid>
</Window>
XAML.cs:
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
}
ViewModel.cs:
public class ViewModel
{
private ICommand _testCommand;
public ICommand TestCommand
{
get { return _testCommand ?? (_testCommand = new RelayCommand(_testExecute)); }
}
private void _testExecute(object s)
{
Trace.WriteLine(s + "Worked!!");
}
}
输出: TesterWorked!!