WPF ScrollIntoView奇怪的行为

时间:2017-11-13 14:04:55

标签: wpf xaml

我',使用ScrollIntoView滚动到列表中最顶层的项目(默认情况下,它总是滚动到底部项目,但在某些特定情况下我需要另一种方式)

因此首先将项目添加到列表中,然后调用ScrollIntoView(Items[0])。 ScrollIntoView在Dispatcher.BeginInvoke内调用,因此它位于UI线程中。

一般的想法是用户看到包含项目“简短”描述的初始列表,然后选择其中一个,并查看所有信息,其中也包含“短”部分。

即:

1)

enter image description here

2)

enter image description here

因此,当我点击案例1中的元素1时,我希望看到图片2.但有时我会看到

enter image description here

我注意到,例如,当光标停留在列表框上时,视图总是正确更新。我已经检查了“AddItem”和“ScrollTop”方法的callstack,它们的顺序正确,并且“ScrollTop”总是被正确调用。

在所有其他情况下(当我拿起第2项或第0项时)“ScrollTop”运作良好。

所以我认为这是某种WPF优化。因为1)中的第1项信息与案例2)中的第1项信息相同且位于同一位置。每次WPF都不会更新视图。

有没有办法,每次滚动到顶部后都要更新列表框?

我试过UpdateLayout()。它没有帮助。

更新(代码示例): 主线程代码:

UIManager.AddListItem(item1);
UIManager.AddListItem(item2);
UIManager.AddListItem(item3);
UIManager.ScrollToTop();

UIManager实施:

public void AddListItem(ListItem item)
{
 ExecuteUI(() =>
 {
  MyList.AddItem(item);
 });
}

public void ScrollToTop()
{
 ExecuteUI(() =>
 {
  MyList.ScrollToTop();
 });
}

MyListModel实现:

public void AddItem(ListItem item)
{
 lock (linesLock)
 {
   if (Lines == null)
     Lines = new ObservableCollection<ItemModel>();

   ItemModel line = new ItemModel(item); 
   Lines.Add(line); //When line added it automatically scrolls to it
  // via ((INotifyCollectionChanged)ListLines.Items).CollectionChanged += LinesChanged;    
 }
}

public void ScrollToTop()
{
   if (Lines.Count == 0 || ScrollEvent == null)
            return;
    ScrollEvent(this, new ScrollEventArgs(Lines[0]));
   // via Model.ScrollEvent += ScrollEvent;
}

模型xaml代码:

// ListLines is a ListBox

private void LinesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
        ListLines.ScrollIntoView(e.NewItems[0]);
}

private void ScrollEvent(object sender, ScrollEventArgs e)
{
  ListLines.ScrollIntoView(e.Item);
}

1 个答案:

答案 0 :(得分:0)

尝试使用ScrollToVerticalOffset的{​​{1}}或ScrollToTop方法:

ScrollViewer

但请始终记得在提问时提供Minimal, Complete, and Verifiable example您的问题。

相关问题