我希望将一个窗口级别的KeyBinding与命令参数作为窗口本身。
e.g。
<KeyBinding Command="{Binding CloseCommand}" CommandParameter="{Binding ElementName=mainWindow}" Key="Esc"/>
绑定有效,但参数为null。有什么工作?
以下是我的命令:`
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("Action excute is null");
_execute = execute;
_canExecute = canExecute;
}
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
答案 0 :(得分:1)
实际上这对我有用 - 但我正在使用[MVVM Light Toolkit 1的RelayCommand<FrameworkElement>
。
<Window.InputBindings>
<KeyBinding Command="{Binding MyCommand, ElementName=MainRoot}" CommandParameter="{Binding ElementName=MainRoot}" Key="Esc"/>
</Window.InputBindings>
就我而言,Command
来自DependencyProperty
,但这不会产生很大的影响。
public RelayCommand<FrameworkElement> MyCommand
{
get { return (RelayCommand<FrameworkElement>)GetValue(MyCommandProperty); }
set { SetValue(MyCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for MyCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyCommandProperty =
DependencyProperty.Register("MyCommand", typeof(RelayCommand<FrameworkElement>), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
MyCommand = new RelayCommand<FrameworkElement>(DoSthYo);
}
public void DoSthYo(FrameworkElement fwE)
{
var x = fwE;
}
因为这是有效的 - 我认为你的Command
可能不支持CommandParameter
。
答案 1 :(得分:0)
我的建议是在RelativeSource
绑定中使用CommandParameter
:
<Window.InputBindings>
<KeyBinding Command="{x:Static local:CloseWindowCommand.Instance}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Key="Esc" />
</Window.InputBindings>
通过这种方式,您的绑定可以与Window
的名称无关。
然后,您可以创建一个static
命令来关闭应用程序的每个窗口:
public class CloseWindowCommand : ICommand
{
public static readonly ICommand instance = new CloseWindowCommand();
public event EventHandler CanExecuteChanged;
private CloseWindowCommand()
{
}
public bool CanExecute(object parameter)
{
return (parameter is Window);
}
public void Execute(object parameter)
{
Window win;
if (CanExecute(parameter))
{
win = (Window)parameter;
win.Close();
}
}
}
我希望它可以帮到你。