Is there a standard way of doing that?
No. What you are describing is not a standard behaviour.
Since an item in the ListView
is actually selected as you press the up and down keys on the keyboard (without pressing ENTER
), you really have no other choice than to handle a key and a mouse event I am afraid.
But this should be a pretty easy thing to implement. You could for example handle the PreviewKeyDown
event for the ListView
and the PreviewMouseLeftButtonDown
event for the ListViewItem containers.
Please refer to the following sample code.
<ListView x:Name="lv" PreviewKeyDown="lv_PreviewKeyDown">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="lv_PreviewMouseLeftButtonDown" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
public MainWindow()
{
InitializeComponent();
lv.ItemsSource = new List<string> { "1", "2", "3" };
}
private void lv_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show((sender as ListViewItem).DataContext.ToString());
}
private void lv_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show(lv.SelectedItem.ToString());
}
}
It is not "fishy" to implement some custom behaviour :)