【问题标题】:WPF calling commands via eventsWPF 通过事件调用命令
【发布时间】:2010-11-06 02:50:45
【问题描述】:

是否可以通过 WPF 中的事件调用命令?

我有一个保存按钮,按下时会调用命令,当你完成编辑文本框时按下它,它还会将对象作为命令参数传递

 <Button Content="Save"  Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />

我最理想的做法是在文本框失去焦点时调用此命令并将对象作为参数传递,而不必按下按钮,例如:

 <Button LostFocus="{Binding SaveQueueTimeCommand}" />

并且仍然以某种方式将对象作为参数传递。 有没有办法在不使用代码的情况下实现这一点,因为我正在使用 MVVM 模式

感谢您的宝贵时间

【问题讨论】:

    标签: wpf events command


    【解决方案1】:

    最简单的方法是使用交互触发器。

    <Grid xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SomeEvent">
                <i:InvokeCommandAction Command="{Binding Path=SomeCommand, Mode=OneWay}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Grid>
    

    为了后代,我添加了这个。

    【讨论】:

    【解决方案2】:

    您可以使用附加行为来实现此目的。 Marlon Grech 编写了 Attached Command Behaviors 库来为您省去麻烦。用法如下所示:

    <Grid>
        <local:CommandBehaviorCollection.Behaviors>
            <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
        </local:CommandBehaviorCollection.Behaviors>
    </Grid>
    

    【讨论】:

      【解决方案3】:

      恐怕我认为你想做的事情是不可能的。命令不是委托,因此您不能将命令写入事件。我认为您最好的选择是处理Button.LostFocus 事件,然后从处理程序手动执行命令。

      在使用MVVM的时候把代码放在后面的代码中并没有错,只是最好将其最小化,保留代码只用于查看相关任务。我将这个代码视图称为相关,所以它会找到将代码放在代码后面。

      【讨论】:

      • 最终,其他答案清楚地表明它可能的(虽然不是真的直接)。
      【解决方案4】:
      <Grid MouseRightButtonDown ="{eb:EventBinding Command=SomeCommand, CommandParameter=$e}">
      
      </Grid>
      

      命令

      {eb:EventBinding} (Simple naming pattern to find Command)
      
      {eb:EventBinding Command=CommandName}
      

      命令参数

      $e (EventAgrs) 
      
      $this or $this.Property
      
      string
      

      https://github.com/JonghoL/EventBindingMarkup

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2012-01-09
        • 2012-08-26
        • 2011-01-14
        • 1970-01-01
        • 2014-05-02
        相关资源
        最近更新 更多