1

In my WPF application I have a button in each row of a data grid that is bound to a RelayCommand. If someone clicks the button in a row, the underlying method of the command is executed.

Unfortunately, this works just on the second click! The first time I click on the button in the row, only the row is selected. At the second click the command is executed.

If I select the row before, then it works on the first click on the button.

What am I doing wrong?

XAML:

<DataGrid AutoGenerateColumns="False" 
          IsReadOnly="True" 
          Style="{StaticResource DataGridStyle}"
          ItemsSource="{Binding Path=Rows, Mode=OneWay}" 
          SelectedItem="{Binding Path=SelectedRow}">

<DataGrid.Columns>
    <DataGridTextColumn Header="Number" 
                        Width="Auto"
                        Binding="{Binding Path=Number}" />
    <DataGridTemplateColumn Header= "Cancel"
                            Width="Auto"  >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Command="{Binding RelativeSource={RelativeSource 
                                                          AncestorType=Expander}, 
                                          Path=DataContext.CancelCommand}" 
                        HorizontalAlignment="Center" 
                        Width="20" 
                        IsEnabled="{Binding IsCancelable}"
                        Visibility="{Binding RelativeSource={RelativeSource 
                                             AncestorType=DataGrid}, 
                                             Path=DataContext.PermissionToWrite, 
                                             Converter={StaticResource 
                                                      boolToVisibilityConverter}}"
                         >X</Button>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122

1 Answers1

0

I am currently facing the same Issue. I have found that If I click somewhere on the Datagrid first, then the button works. However, If you programatically select the row by using Datagrid.SelectAll() or Datagrid.SelectedItem = ..., then it still doesnt work. The workaround I found is to set the row as being edited when you mouse over the row. You can do this with the following style:

    <Page.Resources>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="IsEditing" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Page.Resources>

This seems to work even if you have expressly set a column as not editable.

Luke Vanzweden
  • 466
  • 3
  • 15