SuN
SuN

Reputation: 471

WPF: ListView Cannot Get Focus when Click in Blank Area

ListView can only get focus when clicking on listview items. When clicking on blank area, which is also part of the listview, focus cannot be got.

Example:

      <Grid>
            <ListView x:Name="lv" 
                      GotFocus="Lv_OnGotFocus"
                      LostFocus="Lv_OnLostFocus"
                      MouseEnter="Lv_OnMouseEnter">
                <ListViewItem>Foo</ListViewItem>
                <ListViewItem>Bar</ListViewItem>
            </ListView>
        </Grid>

Mouse Move In Area

In code above I bind event handler to the listview not the listview item.

How to get focus when any part of listview is clicked ?

WHY I need focus on blank area?

I'm implementing file Copy & Paste function in the listview, in which listview items bind to files on disk. Paste action is triggered by a PreviewKeyDown handler attached to the listview, in which Ctrl + V key press is checked.

If a folder is empty, the listview is empty. Thus PreviewKeyDown handler cannot be triggered , as the Lv_OnGotFocus handler, in a empty folder, Whereas copying file into empty folder meant to be work.

Upvotes: 1

Views: 595

Answers (1)

Sinatr
Sinatr

Reputation: 21999

An easy workaround is to handle clicks:

<ListView PreviewMouseLeftButtonDown="ListView_PreviewMouseLeftButtonDown" ... />

to set focus

void ListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) =>
    (sender as ListBox)?.Focus();

Note: this will cause GotFocus to be called twice when clicking on normal items.

Upvotes: 1

Related Questions