R – Silverlight Datagrid Refresh Data with SelectionChanged Binding

datagrideventssilverlight

I am building an issue tracking system that uses Silverlight. I use DataGrids to display the issue lists, set the selected index to -1 so that no row appears selected and then use the selection change event to popup an issue details window for the particular selected issue.

When I try to refresh the DataGrid by rebinding it to its ItemsSource, I disable the SelectionChanged event, rebind the DataGrid to its ItemsSource, set the SelectedIndex to -1 and then enable the SelectionChanged event again. However, no matter how late I leave the re-enabling of the SelectionChanged event (even until after the DataGrid_Loaded event), a SelectionChanged event is fired and the issue details window pops up.

Is there a better way to refresh the data in a DataGrid that won't cause the SelectedIndex to change? If not, is there a way of telling which events are caused by a programmatic index change and not a human interaction?

(Also up for discussion, is this the best control for the job? I need to display multiple fields per row, such as the issue title, assigned user, requested by user, status, etc.)

Thanks in advance.

Best Answer

I have had a similar issue in the past with the comctl32 ListView control's selection events: Programmatic selection cause selection change events to be raised.

My workaround for this issue is to have a per-grid/list counter variable that lets the event handler know if it should care about the selection event or not. The code would go something like:

int issueList_ProgrammaticEventCount_Selection = 0;

void refreshIssueList()
{
    ++issueList_ProgrammaticEventCount_Selection;
    issueList.ItemsSource = ...;
}

void issueList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (issueList_ProgrammaticEventCount_Selection > 0)
    {
        --issueList_ProgrammaticEventCount_Selection;
        return;
    }

    showIssueDetails();
}
Related Topic