C# 在 ListView WPF 中设置项目焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11745028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:03:45  来源:igfitidea点击:

Set Item Focus in ListView WPF

c#.netwpffocuswpf-controls

提问by jnovacho

is there any way to accomplish this functionality from WinForms in WPF?

有什么方法可以从 WPF 中的 WinForms 完成此功能吗?

ListView.FocusedItem = ListView.Items[itemToFocusIndex]

I'm trying to manually set focus(not select) on item in WPF ListView. From System.Windows.Controls. Thanks.

我正在尝试在 WPF ListView 中的项目上手动设置焦点(而不是选择)。从System.Windows.Controls。谢谢。

采纳答案by Adi Lester

There are two types of focus in WPF - Keyboard Focus and Logical Focus. This linkcan give you more information about focus in WPF.

WPF 中有两种类型的焦点 - 键盘焦点和逻辑焦点。此链接可为您提供有关 WPF 中焦点的更多信息。

You can either do this:

你可以这样做:

ListViewItem item = myListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
item.Focus();

It's also possible to call

也可以打电话

Keyboard.Focus(item); 

If you also want to scroll the ListViewto the item's position, add this:

如果您还想滚动ListView到项目的位置,请添加以下内容:

myListView.ScrollIntoView(item);

IMPORTANT NOTE:For this to work, you will need to set VirtualizingStackPanel.IsVirtualizing="False"on your ListView, which may cause it to perform slower. The reason this attached property is required is that when the ListViewis virtualized (which it is by default), the ListViewItemsaren't created for items that aren't displayed on the screen, which will cause ContainerFromIndex()to return null.

重要说明:要使其正常工作,您需要在VirtualizingStackPanel.IsVirtualizing="False"上进行设置ListView,这可能会导致其执行速度变慢。需要此附加属性的原因是,当ListView虚拟化(默认情况下)时,ListViewItems不会为屏幕上未显示的项目创建 ,这将导致ContainerFromIndex()return null

回答by Josh

I believe you can use Keyboard.FocusedElement to get the focused element in the listview.

我相信您可以使用 Keyboard.FocusedElement 来获取列表视图中的焦点元素。

Keyboard.FocusedElement

should return the focused element

应该返回焦点元素

回答by Zac

    public void foucusItem( ListView.Item itemToFocusIndex){
         int count = 0; 
         foreach(ListView.Item item in YourListView){
               if(item == itemsToFocusIndex){
                     ListView.Items[count].Focus();
                     return;
               }
         count++;
         }
    }

回答by rony sc

//to set focus write
CollistView7.Items[TheIndItem].Selected = true; 
CollistView7.Select();
CollistView7.Items[TheIndItem].Focused = true;
//when TheIndItem is the index

回答by Ahmad

ListView items are UIElements, so simply use UIElement.Focus(). e.g., listViewItem.Focus()or button.Focus()and so on.

ListView 项是 UIElements,因此只需使用UIElement.Focus(). 例如,listViewItem.Focus()button.Focus()等等。