Problem explained:
Given a list containing 10 items.
For example:
listView.SelectedIndex = 4;
//or
listView.SelectedItems.Add(listView.Items[4]);
The item is correctly selected.
One solution was to simulate a mouse click event, which worked but had side effects. Its also way to hacky.
It seems that the mouse event stores the starting item.
Is there something I have overlooked?
I've asked on MSDN about this issue. Surprisingly the cause of this problem is SelectionMode
The problem may be in the ListBox code (ListView derives from ListBox):
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{ ...
if ((this.SelectionMode == SelectionMode.Single) && (base.SelectedItem != null))
{
...
if (selectedItem != null)
{
this.UpdateAnchorAndActionItem(selectedItem);
}
}
The UpdateAnchorAndActionItem(selectedItem) is not called if the SelectionMode is Extended.
So, in the code behind you have to do next:
list.SelectionMode = SelectionMode.Single;
list.SelectedIndex = 4;
list.SelectionMode = SelectionMode.Extended;
Don't quite understand how be in case of MVVM.
Upd1
I have created custom ListView. It will do inside the mentioned above logic. In this case it must work as you expect even in MVVM. I hope it will help you.
public class MyListView:ListView
{
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
//if it is multiselection than execute standard logic
if(SelectedItems.Count!=1)
{
base.OnSelectionChanged(e);
return;
}
var mode = SelectionMode;
SelectionMode = SelectionMode.Single;
base.OnSelectionChanged(e);
SelectionMode=mode;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With