[英]Scroll to bottom of listbox wp7
我有很多项目(0-100)最终需要滚动到包含它的Listbox的底部。我试过:
ScrollViewer.SetVerticalScrollBarVisibility(listmy, ScrollBarVisibility.Auto);
listmy.SelectedItem = listmy.Items.Count-1;
listmy.ScrollIntoView(listmy.SelectedItem);
ScrollViewer.SetVerticalScrollBarVisibility(listmy, ScrollBarVisibility.Disabled);
但是这对我不起作用。scrollviewer包装了列表框和文本框。(列表框垂直滚动处于禁用状态)。 UPD xaml:
<Grid>
<ScrollViewer Name="_ScrollViewer" VerticalScrollBarVisibility="Auto">
<StackPanel Name="stackPanel" Height="auto">
<ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled" x:Name="listmy">
<ListBox.ItemTemplate>
<DataTemplate>...
和cs:
listmy.ItemsSource = ((App)Application.Current).DIALOG;
ScrollViewer.SetVerticalScrollBarVisibility(listmy, ScrollBarVisibility.Auto);
listmy.SelectedIndex = listmy.Items.Count-1;
listmy.ScrollIntoView(listmy.SelectedItem);
ScrollViewer.SetVerticalScrollBarVisibility(listmy, ScrollBarVisibility.Disabled);
我收集你实际上想要确保ListBox的ScrollBar始终完全滚动到底部。 其他解决方案只是确保最后一行是可见的(不一样)。
要获得您想要的效果,您可以创建一个简单的子类ListBox,如下所示:
using System.Windows.Controls;
namespace ScrollBarTest
{
public class CustomListBox : ListBox
{
public void ScrollToBottom()
{
var scrollviewer = GetTemplateChild("ScrollViewer") as ScrollViewer;
scrollviewer.ScrollToVerticalOffset(scrollviewer.ScrollableHeight);
}
}
}
不要像在示例中那样使用外部ScrollViewer,只使用子类ListBox
只要你想滚动到最后一行,就调用ScrollToBottom()方法。
子类化的原因是GetTemplateChild
protected
因此无法从派生类外部访问。
这个怎么样:
var lastItem = listmy.Items[listmy.Items.Count - 1];
listmy.ScrollIntoView(lastItem);
我在一个示例项目上尝试过,它运行得很好!
碰到这一个,并没有找到“开箱即用的工作没有代码隐藏”的解决方案,所以我想出了这个类:
using System.Windows.Controls;
/// <summary>
/// A list box which automatically scrolls to the last line if new items were added.
/// </summary>
public class AutoscrollListBox : ListBox
{
/// <summary>
/// The on items changed.
/// </summary>
/// <param name="e">
/// The e.
/// </param>
protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.ScrollDown();
base.OnItemsChanged(e);
}
/// <summary>
/// Scrolls to the last element.
/// </summary>
private void ScrollDown()
{
if (this.Items.Count > 0)
{
var lastItem = this.Items[this.Items.Count - 1];
this.ScrollIntoView(lastItem);
}
}
}
只需使用此列表框,不需要额外的“魔法”。
如果您只是设置ListBox的选择索引,它应该工作。 我尝试过,似乎工作正常。
listBox1.SelectedIndex = listBox1.Items.Count - 1;
我试过了,它滚动到ListBox的底部,没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.