1
votes

I have a datagrid in Silverlight that has a template column in it containing a button. Looks basically like this in XAML -

<sdk:DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding Selected, Mode=TwoWay}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button HorizontalAlignment="Right" Click="btn_Click">
                                <StackPanel Orientation="Horizontal">
                                    <Image Source="/image.png"/>
                                </StackPanel>
                            </Button>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
                <!-- Ten Other Columns -->
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

Now, in this setup, the btn_Click event fires fine whenever that button is clicked (regardless of whether or not the row is selected. All is well until I added a selectionchanged event to the datagrid. The first line of XAML is now this -

<sdk:DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding Selected, Mode=TwoWay}" SelectionChanged="dg_SelectionChanged">

Now the btn_Click event will only fire if the button that was clicked is on the currently selected row. Otherwise it fires the selectionchanged event only, and never gets to the button click. The selectionchanged event firing I understand, because you are obviously switching the selected row. But what I don't understand is why the btn_Click is never hit. Anyone have ideas on why this is and how to get around it?

Thanks in advance.

2

2 Answers

1
votes

Maybe you thought that Button.Click event never fires because you set breakpoints in btn_Click and dg_SelectionChanged event handlers. In this case debugger enters to dg_SelectionChanged and never in btn_Click. But if you add TextBlock in your view and add something like this:

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            textBlock.Text += "Button.Click ";
        }

        private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            textBlock.Text += "DataGrid.SelectionChanged ";
        }

you can see that both events raise fine.

0
votes

I found out what the problem was. I had a Silverlight toolkit busy indicator that was wrapping this grid (as well as it's containing layout grid). On the SelectionChanged event I switched the busy indicator IsBusy property to true. Apparently this causes all events that would have fired underneath that busy indicator to cancel (including my btn_Click) event. So, to answer my question: The SelectionChanged didn't kill the event, it was calling the busy indicator from inside the selectionchanged event that killed the btn_Click.