Reputation: 794
I have two list box in WPF
which looks something like this:
Lets say, the left one is lbLeft and right one is lbRight.
The ">" button adds one selected item from lbLeft to lbRight. And, "<" removes the selected item form lbRight from the list.
The ">>" adds all the item from lbLeft to lbRight and "<<" clears lbRight.
When I double click an item from lbLeft, it is added to the lbLeft and that newly added item is focused. Also, if i try to add an item from lbLeft which already exists in lbRight, it places a focus in that selected item(so that items are not repeated). But when lots of item are added in lbRight, I have to manually scroll down to the point where focus is placed. How can I make the scrolling of listbox
automatic to the point where focus is placed?
I have done the following:
private void select_Click(object sender, RoutedEventArgs e) // > button
{
addingItemToSelectedList();
}
private void remove_Click(object sender, RoutedEventArgs e) // < button
{
if (lbRight.SelectedItem != null) {
lbRight.Items.RemoveAt(lbRight.SelectedIndex);
}
}
private void selectall_Click(object sender, RoutedEventArgs e) // >> button
{
lbRight.Items.Clear();
foreach (string item in column1) {
lbRight.Items.Add(item);
}
}
private void lbLeft_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
addingItemToSelectedList();
}
private void addingItemToSelectedList() {
if (lbLeft.SelectedItem != null)
{
string item = lbLeft.SelectedItem.ToString();
addFocus(item);
}
}
private void addFocus(string item) {
if (!lbRight.Items.Contains(item))
{
lbRight.Items.Add(item);
lbRight.SelectedIndex = lbRight.Items.Count - 1;
lbRight.Focus();
}
else
{
int index = lbRight.Items.IndexOf(item);
lbRight.SelectedIndex = index;
lbRight.Focus();
}
}
private void removeall_Click_1(object sender, RoutedEventArgs e) //<< button
{
lbRight.ItemsSource = null;
lbRight.Items.Clear();
}
column1 in the code is a list of items which populate lbLeft.
UPDATE:
I tried to use lbRight.ScrollIntoView(lbRight.SelectedIndex);
But it has no effect
Upvotes: 2
Views: 1309
Reputation: 794
ScrollIntoView()
worked now. What i had to do was:
lbRight.ScrollIntoView(lbRight.Items[lbRight.SelectedIndex]);
It now passes the actual item rather than index of it.
Upvotes: 2