为什么不触发DataGrid中按钮的click事件?

时间:2014-07-10 17:03:41

标签: wpf button mvvm datagrid mvvm-light

我正在使用MVVM模式和MVVM Light将事件转换为命令,在我的XAML中我有这样的代码:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Content="+" Padding="0,0,0,0" Height="Auto">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <i:InvokeCommandAction Command="{Binding MyCommand}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

在我的视图模型中,我有这段代码:

private RelayCommand<SelectionChangedEventArgs> _myCommand;
public RelayCommand<SelectionChangedEventArgs> MyCommandCommand
{
    get { return _myCommand ?? (_myCommand = new RelayCommand<SelectionChangedEventArgs>(myCommandCommand)); }
}

private void myCommand(SelectionChangedEventArgs e)
{
    // code
}

但是没有触发click事件。但是,我使用这种方式为我的应用程序中的每个按钮,当按钮进入用户控件或窗口时,事件被触发。

感谢。

2 个答案:

答案 0 :(得分:2)

更改您的绑定,它DataContext正在寻找的DataContext Template <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.MyCommand}" / 根据您的结构可能会有所不同。

将其更改为此

{{1}}

答案 1 :(得分:0)

除了上述答案,我还发现有必要在Xaml中指定ClickMode =“ Press”。

<Button Content="&#xE16F;" Focusable="True" FontFamily="Segoe UI Symbol" FontSize="16" Background="{StaticResource HeroLightGray}" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center" 
ClickMode="Press" 
Command="{Binding DataContext.CopyMetadataSourceAsync, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" CommandParameter="{Binding .}" />

我不记得以前必须这样做,但是在花了数小时进行故障排除,将RelayCommand转换为IAsyncCommand等之后,这是唯一可行的方法。实际上,除非我添加了ClickMode =“ Press”,否则我什至无法触发常规的“ Click event”方法背后的代码!