在样式的EventTrigger中触发一个命令?

12

如您所知,您无法直接将事件与命令绑定,而不使用行为:

<DataGrid>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding TradeEntryCommand"} />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>

这个代码完全正常,但我现在需要从双击DataGrid本身改为双击单元格(我不关心点击了哪个单元格)。

我希望像这样在单元格样式中定义这个行为:

<Style x:Key="DefaultCellStyleBase" TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <ControlTemplate.Triggers>
                    <EventTrigger RoutedEvent="PreviewMouseDoubleClick">
                        ?????????
                    </EventTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <!-- ... -->
</Style>

但是我应该如何将上述行为引入以触发命令?

非常感谢。


在SO上已经有很多关于在样式中定义行为的重复问题了。简而言之:你不能这样做,至少不是不经过大量复杂的代码操作。我喜欢EventToCommand行为,但在这种情况下,我总是只能使用一个带有方法处理程序的常规EventSetter,在视图上执行视图模型命令。它感觉很肮脏,看起来很丑陋,因为涉及到所有的空值检查,但是如果你发现自己在一个大型应用程序中遇到这个问题很多次,那么看一下这些“解决方案”可能还是比较简单的。 - Sean Hanley
2个回答

9

由于您正在重新模板化DataGridCell,因此可以将触发器添加到控件模板中的根元素中。类似这样:

<ControlTemplate TargetType="{x:Type DataGridCell}">
    <Grid x:Name="root" Background="Transparent">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewMouseDoubleClick">
                <i:InvokeCommandAction Command="{Binding TradeEntryCommand}" />
            </i:EventTrigger>                            
        </i:Interaction.Triggers>
    </Grid>
</ControlTemplate>

虽然代码正在构建,但我无法正确获取DataContext,因为它位于未指定的位置。我甚至尝试了以下方法,但没有成功:<i:InvokeCommandAction Command="{Binding TradeEntryCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Views:MainWindow}}" />。 - Houman
1
@Kave - 请尝试:Command="{Binding DataContext.TradeEntryCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Views:MainWindow}}" - CodeNaked

3
这是我在类似情况下为按钮命令使用的版本(按钮在DataGridRow中,DataGrid上的命令应该由按钮调用,我需要在我的命令中使用行的DataContext)。您将不得不使用doubleClick触发器的InvokeCommandAction的命令,但我想这样也可以工作。祝好运!
    <DataTemplate>
            <TextBlock>                             
           <Button x:Name="cmdButton"                            
                                    Command="{Binding Path=DataContext.CommandNameInViewModel, 
                                        RelativeSource={RelativeSource AncestorType={x:Type TypeOfAncestorWithTheViewModel}}}"
                                    CommandParameter="{Binding}" >      
                                    Do something
        </Button>

    </TextBlock>  
</DataTemplate>     

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接