[英]How to Autoscroll listbox to bottom wpf c#?
我有一個列表框,我將項目動態添加到列表框中。
我希望列表框自動滾動到添加的最后一項。
我用了
List<string> ItemsList = new List<string>
public void InsertItem(string newItem)
{
ItemsList.Add(status);
if (ItemsList.Count > MaxSize)
{
ItemsList.RemoveAt(0);
}
lb.Items.Refresh();
lb.SelectedIndex = lb.Items.Count - 1;
lb.ScrollIntoView(status);
}
但這僅在我的應用程序初始化之前有效(即我在應用程序啟動之前添加了一些項目)
但是在應用程序啟動后,如果我嘗試添加項目,則滾動條不會自動滾動到最后添加的項目
任何人都可以告訴解決方案
實際上,這確實是一個使命,因為ScrollIntoView僅在首次調用時起作用。 此后的其他所有呼叫由於某種原因將無法工作。
解決此問題的方法是找到列表框的“ ScrollInfo”並設置滾動值。 見下面的例子
public static void AutoScrollToCurrentItem(ListBox listBox, int index)
{
// Find a container
UIElement container = null;
for (int i = index; i > 0; i--)
{
container = listBox.ItemContainerGenerator.ContainerFromIndex(i) as UIElement;
if (container != null)
{
break;
}
}
if (container == null)
return;
// Find the ScrollContentPresenter
ScrollContentPresenter presenter = null;
for (Visual vis = container; vis != null && vis != listBox; vis = VisualTreeHelper.GetParent(vis) as Visual)
if ((presenter = vis as ScrollContentPresenter) != null)
break;
if (presenter == null)
return;
// Find the IScrollInfo
var scrollInfo =
!presenter.CanContentScroll ? presenter :
presenter.Content as IScrollInfo ??
FirstVisualChild(presenter.Content as ItemsPresenter) as IScrollInfo ??
presenter;
// Find the amount of items that is "Visible" in the ListBox
var height = (container as ListBoxItem).ActualHeight;
var lbHeight = listBox.ActualHeight;
var showCount = (int)(lbHeight / height) - 1;
//Set the scrollbar
if (scrollInfo.CanVerticallyScroll)
scrollInfo.SetVerticalOffset(index - showCount);
}
private static DependencyObject FirstVisualChild(Visual visual)
{
if (visual == null) return null;
if (VisualTreeHelper.GetChildrenCount(visual) == 0) return null;
return VisualTreeHelper.GetChild(visual, 0);
}
使用上面的代碼的方式可以是這樣的:
private void Button_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Add("New Item");
AutoScrollToCurrentItem(listBox1, listBox1.Items.Count);
}
我真的希望我有足夠的觀點來評論您的問題。 您的ItemsList如何連接到ListBox? 啟動應用程序后,可以手動向下滾動到新項目嗎?
您很可能將ItemsList綁定到ListBox。 如果是這樣,我建議您將List<string>
更改為ObservableCollection<string>
以便ListBox可以自動更新。
如果您可以自動更新列表框,則使用ObservableCollection。
private ObservableCollection<string> _source = new ObservableCollection<string>();
和您的插入方法:
private void Insert(string item)
{
_source.Add(item);
lb.SelectedIndex = _source.Count - 1;
lb.ScrollIntoView(ListBox.SelectedItem);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.