WPF listview selection problem
I have a listview (in extended selection mode and synchronized with the current item) and a textbox. The textbox allows the user to input search criteria. On the TextChanged event of the listbox I match the search criteria to the names of listviewitems in the listview and set the selectedindex accordingly. This is to both highlight it and provide an easy selection point to select further points from. See the code below:
void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
TextBox textBox = (TextB开发者_开发百科ox)sender;
if (textBox != null)
{
string text = textBox.Text;
if (text != string.Empty)
{
for (int i = 0; i < listViewPerson.Items.Count; i++)
{
Person person = (Person)listViewPerson.Items[i];
if (person != null)
{
if (person .Name.StartsWith(text, StringComparison.OrdinalIgnoreCase))
{
listViewPerson.SelectedIndex = i;
listViewPerson.ScrollIntoView(routePoint);
break;
}
}
}
}
else
{
listViewPerson.SelectedIndex = -1;
}
}
}
catch (Exception Caught)
{
Log.AddExceptionEntry(this, "Could not search ", Caught, Log.Target.All,
Log.EntryType.Error);
}
}
The searching and selection works just fine. On the first attempt the user can select a second point (the first is already selected by the search) and multi-select from the first without a problem.
However 2nd time round the listview continues to 'remember' the first selected point from the first search (which was originally set by the search routine), therefore causing the selection to start from the wrong place (even though the selectedindex is correctly set to the new item in the listview).
However, a mouse click on the selectedindex then causes the selection point to be reset correcty. It seems like selectedindex works differently in code compared to using manual clicks.
I've tried using listViewTrainServiceHelperPattern.SelectedItems.Clear(), SelectedValue(object) instead of SelectedIndex, but all to no avail. Does anyone have any idea what is causing this and how to work around it?
This sounds similar to a Wpf treeview bug where if you set the IsSelected on an item through a binding, the logical focus remains with the previously selected item. Try getting a handle to the newly selected ListViewItem using ListView.ItemContainerGenerator.ContainerFromItem(newlySelectedItem) and then call focus() on it. I'd be really interested to hear if this works for you.
精彩评论