XAML ContextMenu gets bound to wrong row in a DataGrid

Posted by Simon_Weaver on Stack Overflow See other posts from Stack Overflow or by Simon_Weaver
Published on 2010-05-05T21:19:59Z Indexed on 2010/05/12 21:44 UTC
Read the original article Hit count: 453

I have a XAML based ContextMenu bound to the rows in a datagrid. It works just fine - until the grid is scrolled!

This is the context menu for one of the controls in the visual tree or a DataGrid row.

<data:DataGridTemplateColumn Header="Customer Details" Width="*">
    <data:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Grid Background="Transparent"> <!-- allows click in entire cell -->

               <controlsInputToolkit:ContextMenuService.ContextMenu>
                <controlsInputToolkit:ContextMenu>

                    <controlsInputToolkit:MenuItem Header="{Binding CompletedOrderId,StringFormat='Create Reminder for order #\{0\}'}"  
                                       CommandParameter="{Binding}">
                    <controlsInputToolkit:MenuItem.Command>
                        <command:CreateReminderCommand/>
                    </controlsInputToolkit:MenuItem.Command>
                    <controlsInputToolkit:MenuItem.Icon>
                        <Viewbox>
                        <Image Width="19" Height="18" Source="../images/reminders.png" VerticalAlignment="Center"/>
                        </Viewbox>
                    </controlsInputToolkit:MenuItem.Icon>
                    </controlsInputToolkit:MenuItem>

                <controlsInputToolkit:ContextMenu>
                 <controlsInputToolkit:ContextMenuService.ContextMenu>
                 ......

The ICommand is CreateReminderCommand and the CommandParameter is bound to the data item for the row itself.

This works just fine - I can right click on a row and it will show me the correct text in the menu item 'Create Reminder for order 12345'.

Then I scroll the datagrid down a page. If I keep right clicking on items then suddenly I'll see the wrong order number for a row. I think what must be happening is this :

  • The DataGrid is reusing instances of MenuItem that it has previously created.

How can I force a refresh of the ContextMenu when it is displayed for an item that changes? There's no 'Update method on the ContextMenu or ContextMenuService.

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about silverlight-4.0