I have a WPF desktop app, with a ListView that contains some items.
I would like to get a notification when an item is clicked with the mouse, or when it is selected using the keyboard and the user clicks "Enter". The required behavior is similar to that of "Settings" on modern Windows 10 UI), or to that of items on the right side
SelectionChanged won't work for me, because when the user navigates with the keyboard, I only want to perform an action when they click "Enter".
Is there a standard way of doing that? I can catch the keys/mouse events, but it seems like a fishy solution.
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 :)