I can't find the way to programmatically set focused item in WPF ListView. I can only find variations of Selected Item | Items | Index | Value, but 'Focused' item is not directly related to 'selected' item - focused item can be not-selected (e.g. when unselecting current item with Ctrl+Click).
To be short - I'd like to get following behvaiour from the below provided code (it fills dummy list view with dummy 8 items and on pressing X tries to focus 2nd item from the end):
Wanted behaviour:
- using mouse - select 2nd item
- press X - this focuses 2nd item from the end
- press 'Down' array on keyboard - this should move current selection to the last item
What happens actually:
- using mouse - select 2nd item
- press X - this selects 2nd item from the end, but focus remains on the 2nd item from start
- press 'Down' array on keyboard - this should move current selection to the last item, but 3rd item is selected instead.
Note: plain Win32 API (which is, of course, completely different thing from WPF) has LVM_SETSELECTIONMARK message for this. I could not find analogue in WPF. Does it exist?
Sample XAML:
<Window x:Class="WpfListviewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<ListView x:Name="List1" KeyDown="List1_KeyDown">
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Column 1" />
<GridViewColumn Width="140" Header="Column 2" />
<GridViewColumn Width="140" Header="Column 3" />
</GridView>
</ListView.View>
<sys:DateTime>1/2/3</sys:DateTime>
<sys:DateTime>4/5/6</sys:DateTime>
<sys:DateTime>7/8/9</sys:DateTime>
<sys:DateTime>10/11/12</sys:DateTime>
<sys:DateTime>1/2/3</sys:DateTime>
<sys:DateTime>4/5/6</sys:DateTime>
<sys:DateTime>7/8/9</sys:DateTime>
<sys:DateTime>10/11/12</sys:DateTime>
</ListView>
</Window>
Sample code-behind:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void List1_KeyDown(object sender, KeyEventArgs e) {
if( e.Key == Key.X ) {
List1.SelectionMode = SelectionMode.Single;
List1.SelectedIndex = List1.Items.Count - 2;
}
}
}