2
votes

Refreshing my datagrid when my observableCollection gets updated in the viewmodel have been a nightmare. After I discover the DataGrid won't respond to the events raised by the ObservableCollection I discovered DataGrid.Items.Refresh. It does refresh but then the DataGrid loses focus. I have a simple list and I want to change a value when I press a key and then update. Its unacceptable the user have to pick the mouse again when using keyboard shortcuts ... Here is a simple example:

            <DataGrid x:Name="MyDataGrid" SelectionMode="Single" AutoGenerateColumns="False" IsReadOnly="True" KeyUp="MyDataGrid_KeyUp">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name" Binding="{Binding Path=First}"/>
                    <DataGridTextColumn Header="Last Name" Binding="{Binding Path=Last}"/>
                </DataGrid.Columns>
            </DataGrid>

And the code behind:

    private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key.Equals(Key.Space))
        {
            MyDataGrid.Items.Refresh();
        }
    }

p.s. In this example I'm setting the ItemsSource in my code behind and not binding to a ObservableCollection. Also i'm using just the codebehind and not a ViewModel but the problem is the same.

edit: The initial problem was that I wasnt using the NotifyPropertyChanged in my class. However, the problem here presented is still "open", I can't really understand the lost focus question when I do the Refresh()

2

2 Answers

1
votes

Refreshing my datagrid when my observableCollection gets updated in the viewmodel have been a nightmare. - Why has this been a nightmare? Should be easy though.

Regarding your problem. Please try the following

private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key.Equals(Key.Space))
    {
        MyDataGrid.Items.Refresh();
        MyDataGrid.Focus();
    }
}

You can find the related doc here.

Edit
Let's try this one

private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key.Equals(Key.Space))
    {
        MyDataGrid.Items.Refresh();
        FocusManager.SetFocusedElement(MyDataGrid);
    }
}

For more information, please have a look here.

0
votes

Scheduling the refresh via dispatcher worked for me (with a TreeView).

So instead of doing this (loses focus):

tree.Items.Refresh();

I do this (does not lose focus):

Dispatcher.BeginInvoke(new Action(() => tree.Items.Refresh()));

No idea why but it works for me.