1

从 WinForm 应用程序调用 WPF KeyBindings 时,我需要一些帮助。我已经创建了我认为是演示问题的基本部分。如果有帮助,我可以提供一个示例应用程序。

WinForm 应用程序启动一个表单,该表单有一个调用 WPF 的按钮

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim view As New WpfPart.MainWindow
    System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(view)
    view.ShowDialog()
End Sub

使用 WPF 视图创建它的视图模型并设置键控:

<Window x:Class="WpfPart.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:WpfPart.ViewModels"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <vm:MainWindowViewModel />
</Window.DataContext>
<Window.InputBindings>
    <KeyBinding Key="Escape" Command="{Binding OpenCommand}" Modifiers="Control" />
</Window.InputBindings>
<Grid>

</Grid>

ViewModel 使用 DelagateCommand 希望将所有内容链接起来

using System;
using System.Windows;
using System.Windows.Input;
using WpfPart.Commands;

namespace WpfPart.ViewModels
{
class MainWindowViewModel
{
    private readonly ICommand openCommand;

    public MainWindowViewModel()
    {
        openCommand = new DelegateCommand(Open, CanOpenCommand);
    }

    public ICommand OpenCommand { get { return openCommand; } }
    private bool CanOpenCommand(object state)
    {
        return true;
    }

    private void Open(object state)
    {
        MessageBox.Show("OpenCommand executed.");
    }
}
}

谁能看到哪里出了问题,按键什么也没做?!?

4

2 回答 2

1

要使 KeyBinding 工作,您需要将 CommandReference 添加到 Window.Resources,然后从 KeyBinding(而不是 Command)中引用 CommandReference。

我还使用 Control-X 来避免在 Windows 中打开映射到 Control-Escape 的“开始”按钮。

这是您可以根据您的问题使用的 XAML:

<Window.Resources>
    <!-- Allows a KeyBinding to be associated with a command defined in the View Model  -->
    <c:CommandReference x:Key="OpenCommandReference" Command="{Binding OpenCommand}" />
</Window.Resources>
<Window.InputBindings>
    <KeyBinding Key="X" Command="{StaticResource OpenCommandReference}" Modifiers="Control" />
</Window.InputBindings>
于 2010-10-06T22:49:26.010 回答
0

在 mi 项目中,我使用了解决方案:假设 ListView 具有带有命令 CmdDelete 的 DummyViewModel 项,并且我需要在选定的项下调用此命令,并预置 Delete 键

<Grid>
    <Button x:Name="DeleteCmdReference" Visibility="Collapsed" Command="{Binding Source={x:Reference MyListView},Path=SelectedItem.CmdDelete}" />
    <ListView x:Name="MyListView" ...="" >
      <ListView.InputBindings>
        <KeyBinding Key="Delete" Command="{Binding ElementName=DeleteCmdReference,Path=Command}"/>
      </ListView.InputBindings>
    </ListView>
  </Grid>
于 2013-04-17T12:26:07.763 回答