0

I have an MVVM application in which the MainWindow contains a grid with several views.

In one of the viewmodels there is a command which I can activate by using hot keys in its corresponding view. I can only activate the command when I am placed in the part of the MainWindow that contains the specific view.

The following code works fine, if I only want to be able to activate the command in the specific view:

ComponentView.xaml:

    ...
    <UserControl.InputBindings>
        <KeyBinding Gesture="CTRL+U" Command="{Binding Path=UploadCmd}"/>
    </UserControl.InputBindings>
</UserControl>


I would like to be able to activate the command by using the hot keys from any part of the MainWindow.

This is my failed attempt to do the keybinding in the MainWindow, so that the command can be activated from anywhere:

MainWindow.xaml:

<Window x:Class="MyProgram.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:view="clr-namespace:MyProgram.View"
        xmlns:vm="clr-namespace:MyProgram.ViewModel"
        ...>
    <Grid>
        // Grid content
    </Grid>
    <Window.DataContext>
        <vm:ComponentViewModel>
            <KeyBinding Gesture="CTRL+U" Command="{Binding Path=UploadCmd}"/>
        </vm:ComponentViewModel>
    </Window.DataContext>
</Window>

Is it possible to somehow let the application know where the command is directly in the xaml?

4

1 回答 1

0

我能想到的三个选项:

  1. 您可以将命令放在主窗口中,然后使用从子视图到主窗口中命令的相对源绑定。

    {绑定路径=PathToProperty,RelativeSource={RelativeSource AncestorType={x:Type Window}}}

  2. 如果您使用的是 mvvm 框架,通常有一种方法可以在视图模型之间进行消息/通信。这通常不是最好的解决方案,但可以在正确的情况下使用。

  3. 使用 IOC / Dependecy Injection 创建一个在视图模型定位器中实例化为单例的服务。然后将此服务实现注入到父视图模型和子视图模型构造函数中。然后,您可以从子视图模型可以访问的父视图模型中调用该服务的函数/属性。我将其用于导航目的。

你想用这些命令做什么?

希望这可以帮助

于 2013-05-09T16:16:00.893 回答