简体   繁体   English

WPF:在空白区域单击时,ListView 无法获得焦点

[英]WPF: ListView Cannot Get Focus when Click in Blank Area

ListView can only get focus when clicking on listview items. ListView 只能在单击 listview 项目时获得焦点。 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>

鼠标移入区域

In code above I bind event handler to the listview not the listview item.在上面的代码中,我将事件处理程序绑定到列表视图而不是列表视图项。

  • When cursor moves in the blank area, Lv_OnMouseEnter handler is triggered, which indicate the blank area are also part of listview.当 cursor 在空白区域移动时,会触发Lv_OnMouseEnter处理程序,这表明空白区域也是列表视图的一部分。
  • When clicking in the blank area, Lv_OnGotFocus is not triggered.在空白区域点击时,不会触发Lv_OnGotFocus Focus not got.没有得到焦点。
  • When clicking on any listview item, Lv_OnGotFocus is triggered.单击任何列表视图项时,会触发Lv_OnGotFocus Focus got.焦点得到了。
  • It's even the SAME, when Lv_OnGotFocus handler was moved to outter Grid .Lv_OnGotFocus处理程序移到外部Grid时,它甚至是相同的。

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.我正在列表视图中实现文件复制和粘贴 function,其中列表视图项绑定到磁盘上的文件。 Paste action is triggered by a PreviewKeyDown handler attached to the listview, in which Ctrl + V key press is checked.粘贴操作由附加到列表视图的PreviewKeyDown处理程序触发,其中检查了Ctrl + V按键。

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.因此PreviewKeyDown处理程序不能被触发,作为Lv_OnGotFocus处理程序,在一个空文件夹中,而将文件复制到空文件夹意味着工作。

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.注意:这将导致GotFocus在单击普通项目时被调用两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM