问题 在样式的EventTrigger中触发命令?


如您所知,在没有行为的情况下,您无法将事件直接绑定到命令:

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

这完全没问题,但是现在我必须通过双击DataGrid本身来双击Cell来重构它。 (我不在乎点击了哪个单元格)

我希望现在在Cell Style中定义这个behviour,如下所示:

<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>

但是我如何从上面引入行为来触发命令呢?

非常感谢,


10102
2018-05-11 09:31


起源

已经在SO上的相当多的欺骗与定义样式中的行为有关。简而言之:你不能,至少不能没有跳过很​​多复杂的代码箍。我喜欢EventToCommand行为,但在这种情况下,我总是只需要在执行viewmodel命令的视图上使用带有方法处理程序的常规EventSetter。它感觉很脏,看起来很丑,所有的空检查都涉及到,但是看过这个“解决方案”它可能仍然比较简单,除非你发现自己在大型应用程序中运行了这么多次。 - Sean Hanley


答案:


由于您正在重新模拟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>

7
2018-05-11 11:54



代码构建时,我无法正确获取DataContext,因为它位于未指定的位置。我甚至尝试了这个没有成功:<i:InvokeCommandAction Command =“{Binding TradeEntryCommand,RelativeSource = {RelativeSource FindAncestor,AncestorType = Views:MainWindow}}”/> - Houman
@Kave - 尝试:Command =“{Binding DataContext.TradeEntryCommand,RelativeSource = {RelativeSource FindAncestor,AncestorType = Views:MainWindow}}” - CodeNaked


这是我在类似情况下用于Button命令的版本(DataGridRow中的Button,DataGrid上的Command应该由Button调用,我需要命令中的行的DataContext)。你必须使用doubleClick-trigger的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>     

3
2018-06-27 09:43