Until now, I have a datagrid which items source was binding to a ObservableCollection in the view model. And if I select an item in the view model, the datagrid scroll to the selected item. For that, I am using an attached behaviour.
But I have a problem, when I sort by a column and I modify the property of the selected item that is source of this column, it is not put in the new position according to the new value.
For that, I use a ICollectionView, so it works in the way that the item is put in the new position, but if it is out of the visible area of the datagrid, it doesn't scroll to the selected item. I guess that the problem is because the behaviour only is fired when the selected item changes.
How could I scroll to the selected item when the collection view is refreshed?
This is the code:
<DataGrid ItemsSource="{Binding IFacturas, IsAsync=true}">
<i:Interaction.Behaviors>
<behaviors:ScrollIntoViewBehavior/>
</i:Interaction.Behaviors>
</DataGrid>
This is the view model:
MyViewModel()
{
MyCollectionViewInViewModel = CollectionViewSource.GetDefaultView(Items);
}
private ObservableCollection<MyClass> _items = new ObservableCollection<MyClass>();
public ObservableCollection<MyClass> Items
{
get { return _items; }
set
{
_items = value;
base.RaisePropertyChangedEvent(nameof(Items));
}
}
private Facturas _itemsSelectedItem;
public Facturas ItemsSelectedItem
{
get { return _itemsSelectedItem; }
set
{
if(_itemsSelectedItem != value)
{
_itemsSelectedItem = value;
base.RaisePropertyChangedEvent(nameof(ItemsSelectedItem));
}
}
}
public ICollectionView MyCollectionViewInViewModel { get; }
Update Item(MyClass paramSelectedItem)
{
SelectedItem
MyCollectionViewInViewModel.Refresh();
//How to do to scroll to the selected item?
}
The behavior:
using Microsoft.Xaml.Behaviors;
using System.Windows.Controls;
public class ScrollIntoViewBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is DataGrid)
{
DataGrid grid = (sender as DataGrid);
if (grid.SelectedItem != null)
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.SelectedItem, null);
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.SelectionChanged -= new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
}
}