Reputation: 1453
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()
Upvotes: 2
Views: 4653
Reputation: 2978
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.
Upvotes: 0
Reputation: 4865
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.
Upvotes: 1