2012-07-31 142 views
7

有沒有什麼辦法可以從WPF的WinForms中完成這個功能?在ListView中設置項焦點WPF

ListView.FocusedItem = ListView.Items[itemToFocusIndex] 

我想手動設置焦點(不選擇)的項目在WPF的ListView。從System.Windows.Controls。 謝謝。

回答

18

有兩種類型的焦點在WPF的 - 鍵盤焦點和邏輯焦點。 This link可以爲您提供有關WPF中焦點的更多信息。

你可以這樣做:

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

它也可以調用

Keyboard.Focus(item); 

如果你也想在ListView滾動到該項目的位置,補充一點:

myListView.ScrollIntoView(item); 

重要提示:爲此, k,您需要在您的ListView上設置VirtualizingStackPanel.IsVirtualizing="False",這可能會導致其執行速度變慢。此附加屬性需要的原因是ListView被虛擬化(默認情況下),ListViewItems不會創建用於屏幕上未顯示的項目,這將導致ContainerFromIndex()返回null

+0

那麼我有你的代碼背後的想法,但它不工作_InListView.Items [itemIndex]作爲IInputElement; _返回_null_。 ListView中的項目是我的自定義類的實例,根據instace屬性在運行時選擇適當的樣式。該類不分別繼承任何類或接口;所以我不能將它轉換爲IInputElement ... – jnovacho 2012-07-31 20:15:03

+0

@jnovacho從UIElement繼承的任何控件實現IInputElement。你從'myListView.Items [itemIndex]'得到什麼類型的對象? – 2012-07-31 20:23:29

+0

我只從該集合中獲得對象。 – jnovacho 2012-07-31 20:31:33

0

我相信你可以使用Keyboard.FocusedElement獲取listview中的焦點元素。

Keyboard.FocusedElement 

應該返回聚焦元素

+0

我不需要獲得關注的項目,我需要**設置**焦點。 – jnovacho 2012-07-31 17:47:09

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

沒有Focus()方法。我正在使用WPF而不是表單! – jnovacho 2012-07-31 18:03:04

+0

確保其Focusable屬性設置爲true。 – Zac 2012-07-31 18:30:20

+0

http://msdn.microsoft.com/en-us/library/system.windows.controls.listview.aspx 我認爲有一個Focus()方法。請查看方法下半部分的鏈接。 – Zac 2012-07-31 18:31:09

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

ListView項是UIElements,所以只需使用UIElement.Focus()。例如listViewItem.Focus()button.Focus()等等。