C# 如何在WPF中使用Prism 6处理ViewModel中的按键事件?
我需要处理一个按键事件,它可以是a-Z,0-9中的任意一个,但我需要在ViewModel中处理它。应将按下的键传递给ViewModel。我使用的是prism 6.0,因此View1ViewModel自动连接到view1 我知道,对于特定的钥匙,我可以处理,但如何对所有钥匙执行相同的操作 我在ViewModel中有一个属性“KeyPressed”,我在代码隐藏中尝试了下面的代码C# 如何在WPF中使用Prism 6处理ViewModel中的按键事件?,c#,wpf,mvvm,prism-6,C#,Wpf,Mvvm,Prism 6,我需要处理一个按键事件,它可以是a-Z,0-9中的任意一个,但我需要在ViewModel中处理它。应将按下的键传递给ViewModel。我使用的是prism 6.0,因此View1ViewModel自动连接到view1 我知道,对于特定的钥匙,我可以处理,但如何对所有钥匙执行相同的操作 我在ViewModel中有一个属性“KeyPressed”,我在代码隐藏中尝试了下面的代码 private void Window_PreviewKeyUp(object sender, KeyEventArgs
private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
_mainWindowViewModel.KeyPressed = e.Key;
}
但是这段代码并没有像Prism框架中的viewmodel那样更新View1ViewModel,视图绑定是通过框架进行的。
我尝试使用交互,我将下面的代码放在根网格部分
<i:Interaction.Triggers >
<i:EventTrigger EventName="KeyUp">
<i:InvokeCommandAction Command="{Binding KeyUpEventCommand}"
CommandParameter="..."/>
</i:EventTrigger>
</i:Interaction.Triggers>
有什么想法/建议我如何处理这个问题吗?命令属性的类型应该是DelegateCommand
:
然后默认情况下,KeyEventArgs
应作为命令参数传递。尝试使用KeyTriger
<i:Interaction.Triggers>
<ei:KeyTrigger Key="Escape">
<i:InvokeCommandAction Command="{Binding KeyDownCommand}" />
</ei:KeyTrigger>
</i:Interaction.Triggers>
public ICommand KeyDownCommand
{
get { return new RelayCommand(KeyboardKeyDownCommand, true); }
}
private void KeyboardKeyDownCommand()
{
///code
}
公共ICommand keydown命令
{
获取{returnnewrelaycommand(KeyboardKeyDownCommand,true);}
}
私有void KeyboardKeyDownCommand()
{
///代码
}
不更新View1ViewModel”的确切含义是什么?会发生什么?是否调用了PreviewKeyUp事件处理程序,但没有调用视图模型的KeyPressed属性的setter?我已经更新了我的问题,KeyUpEventCommand被激发,但它不包含按键的值。视图模型类中的KeyUpEventCommand是如何精确定义的?您可以添加CommandParameter吗?我已经更新了代码。完美!!!这就是我需要的。非常感谢你的回答。但你能解释一下为什么prism:InvokeCommandAction不会启动吗?如果我使用其他键,比如说我先按A,然后我想按B,然后按C。。。每次我按下一个键时都应该执行keyupEvent命令。但这并没有发生,因为该类是Blend SDK的一部分,不支持将EventArgs传递给命令。
public DelegateCommand<KeyEventArgs> KeyUpEventCommand { get; private set; }
private string strAlphabet;
public string Alphabets
{
get { return strAlphabet; }
set { SetProperty(ref strAlphabet, value); }
}
public MainWindowViewModel(IEventAggregator eventAggregator)
{
KeyUpEventCommand = new DelegateCommand<KeyEventArgs>(KeyUpEventHandler);
}
public void KeyUpEventHandler(KeyEventArgs args)
{
//...
}
xmlns:prism="http://prismlibrary.com/"
...
<i:Interaction.Triggers >
<i:EventTrigger EventName="PreviewKeyDown">
<prism:InvokeCommandAction Command="{Binding KeyUpEventCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<i:Interaction.Triggers>
<ei:KeyTrigger Key="Escape">
<i:InvokeCommandAction Command="{Binding KeyDownCommand}" />
</ei:KeyTrigger>
</i:Interaction.Triggers>
public ICommand KeyDownCommand
{
get { return new RelayCommand(KeyboardKeyDownCommand, true); }
}
private void KeyboardKeyDownCommand()
{
///code
}