到目前为止,我有一个datagrid,它的项目源绑定到视图模型中的ObservableCollection。如果我在视图模型中选择一个项目,datagrid就会滚动到所选的项目。为此,我使用了一个附加的行为。
但是我有一个问题,当我按列排序并修改作为此列源的选定项的属性时,它没有根据新值放在新位置。
为此,我使用了ICollectionView,因此它的工作方式是将项放在新位置,但如果它超出了datagrid的可见区域,它就不会滚动到所选项。我猜问题是因为只有在所选项更改时才会触发该行为。
当收藏视图刷新时,如何滚动到选定的项目?
这是代码:
<DataGrid ItemsSource="{Binding IFacturas, IsAsync=true}">
<i:Interaction.Behaviors>
<behaviors:ScrollIntoViewBehavior/>
</i:Interaction.Behaviors>
</DataGrid>
这是视图模型:
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?
}
行为:
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);
}
}
1条答案
按热度按时间whhtz7ly1#
也许试试“重置为空并恢复”技巧?