简体   繁体   English

我如何将此事件处理程序转换为命令?

[英]how do i convert this event handler into a command?

private void GridSplitter_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    vm.positionX = e.GetPosition((sender as GridSplitter).Parent as UIElement).X;
}

the Parent is a VirtualizingStackpanel. Parent是VirtualizingStackpanel。 I kind of understand the idea behind commanding, but am still having trouble understanding how to implement it. 我有点理解指挥背后的想法,但我仍然无法理解如何实现它。 This event handler is taking the X coordinate of the Mouse and sending it to the ViewModel's positionX. 此事件处理程序获取Mouse的X坐标并将其发送到ViewModel的positionX。 If I made this into a command, where would I get the information for sender and e? 如果我把它变成一个命令,我在哪里可以得到发送者和e的信息?

Normally, Commands are used for Button-like controls, that trigger, when the user interacts with them (clicking the button, tapping it, etc.). 通常, Commands用于类似按钮的控件,当用户与它们交互时触发它们(单击按钮,点击它等)。

A Command , depending on your application design and needs, has a CanExecute and an Executed handler or event. 根据您的应用程序设计和需求, Command具有CanExecuteExecuted处理程序或事件。 Those allow you to set, if the Command can execute at all, and what should happen, when it executes. 那些允许你设置,如果Command可以执行,以及什么应该发生,当它执行。

However, you're referring to a PreviewMouseDown event. 但是,您指的是PreviewMouseDown事件。 You cannot prevent the system from firing this event. 您无法阻止系统触发此事件。 So the CanExecute of the new Command is more or less useless in this scenario. 因此,在这种情况下,新CommandCanExecute或多或少无用。

To still achieve your goal, you could use the EventToCommand mechanic, that Ganesh already pointed out in the comments. 为了实现您的目标,您可以使用Ganesh在评论中指出的EventToCommand机制。 This article and the example below should give you a hint, how it will work: 这篇文章和下面的例子应该给你一个提示,它将如何工作:

<ResourceDictionary>
  <DataTemplate x:Key="PreviewMouseDownCommandTemplate">
    <StackPanel>
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseDown">
          <command:EventToCommand Command="{Binding MyCommandProvider.PreviewMouseDownCommand,
                                            Mode=OneWay,
                                            Source={StaticResource Locator}}"
                                  CommandParameter="{Binding Mode=OneWay}" />
        </i:EventTrigger>
      </i:Interaction.Triggers>

      <!-- Content -->

    </StackPanel>
  </DataTemplate>
</ResourceDictionary>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM