WPF ListBox滚动到底部 [英] WPF ListBox Scroll to the bottom
问题描述
我将ObservableCollection用作listBox组件的ItemSource:
I am using ObservableCollection as an ItemSource for my listBox component:
但是控件的行为对我而言是不合适的.我已向下滚动到收藏夹中第一次出现的问题,但没有最后一个出现.
But the behavior of the control is not proper as for me. The matter I have scroll down to ths first occurence in my collection, but not last.
示例列表为:1,1,2,3,4,5,6,7,8,9,11,22,33,1
The sample list is: 1,1,2,3,4,5,6,7,8,9,11,22,33,1
当您输入最后一个1时,组件将向上滚动到第一个1 :).这不是我想要的.
When you enetr last 1 you component scroll up to first 1 :). This not what I am wating for.
请告知.这里是组件代码:
Please advise. Here a code of component:
public class MyListBox : ListBox
{
protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
if (Items.Count > 0)
{
var item = Items[Items.Count - 1];
UpdateLayout();
ScrollIntoView(item);
UpdateLayout();
}
}
}
推荐答案
抱歉,它必须是一个类,因为List或OC会真正进行值比较.因此,您需要使相同的值唯一.我测试了一下,它可以工作.
Sorry but it needs to be a class as a List or OC is going to really do a value comparison. So you need to make identical values unique. I test this out and it works.
<StackPanel Orientation="Vertical" >
<ListBox x:Name="lbStringList" ItemsSource="{Binding Path=UniqueStringList}" DisplayMemberPath="Str" Height="60" VerticalAlignment="Top"/>
<Button Click="Button_Click" Content="56" />
</StackPanel>
private List<UniqueString> uniqueStringList = new List<UniqueString>()
{
new UniqueString("zero",0),
new UniqueString("one",1),
new UniqueString("two",2),
new UniqueString("three",3),
new UniqueString("four",4),
new UniqueString("five",5),
new UniqueString("six",6),
new UniqueString("seven",7),
new UniqueString("zero",8)
};
public MainWindow()
{
InitializeComponent();
}
public List<string> StringList { get { return new List<string>() { "one", "two", "three", "four", "five", "one" }; } }
public List<UniqueString> UniqueStringList
{
get
{
return uniqueStringList;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(sender.GetHashCode());
lbStringList.ScrollIntoView(lbStringList.Items[8]);
}
public class UniqueString
{
private Int32 id;
public string Str { get; private set; }
public override bool Equals(object obj)
{
UniqueString item = (UniqueString)obj;
return item.id == id;
}
public override int GetHashCode()
{
return id;
}
public UniqueString(string str, Int32 _id) { Str = str; id = _id; }
}
这篇关于WPF ListBox滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!