【问题标题】:Why is the click event of a button inside a DataGrid is not fired?为什么不触发 DataGrid 中按钮的单击事件?
【发布时间】:2014-09-01 04:10:17
【问题描述】:

我正在使用 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
}

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

谢谢。

【问题讨论】:

  • 你在哪里定义了命令绑定?

标签: wpf button mvvm datagrid mvvm-light


【解决方案1】:

除了上面的答案,我发现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",否则我什至无法触发常规的代码隐藏“点击事件”方法!

【讨论】:

    【解决方案2】:

    更改您的绑定,它尝试查找的DataContextTemplateDataContext,这可能因您的结构而异。

    改成这个

    <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.MyCommand}" /
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2012-09-12
      • 2019-06-22
      相关资源
      最近更新 更多