问题
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.
The sample list is: 1,1,2,3,4,5,6,7,8,9,11,22,33,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();
}
}
}
回答1:
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; }
}
来源:https://stackoverflow.com/questions/9999859/wpf-listbox-scroll-to-the-bottom