Udostępnij za pośrednictwem


Setting the Initial Focus to a ListView item

This blog describes the steps needed to set the initial keyboard focus to an item in a WPF ListView. The items in the list can be static or data bound. The trick is to access the ListViewItem associated with an item and then set keyboard focus to it.

The following are snippets of the code behind for a dialog with a ListView named myListView and selecting and setting the initial focus to the last item in the list.

Sample Code to Populate the ListView

The for loop populates the list view with some sample items. Note the call to FocusAndSelectItem().

public Window1()
{
    InitializeComponent();

    // Add the items
int itemCount = 50;
for (int i = 0; i < itemCount; i++)
{
ListViewItem item = new ListViewItem();
item.Content = String.Format(CultureInfo.CurrentCulture, "Item {0}", i);
myListView.Items.Add(item);
}

    // Focus and select the last item
FocusAndSelectItem(itemCount - 1);
}

Setting Focus to a ListViewItem

Because the list view and its items may not even be visible when they are created, the code cannot just access the list view item and immediately sets keyboard focus to it. We actually have to defer the focus setting by calling Dispatcher.BeginInvoke() to call back when the application has completed all its initial work and has reached the idle state. FocusAndSelectItem() does this.

In the actual method to set the keyboard focus TryFocusAndSelectItem(), note that we need to ensure that the list view item is visible by calling ScrollIntoView() before setting focus to it.

/// <summary>
/// Request the focus to be set on the specified list view item
/// </summary>
/// <param name="itemIndex">index of item to receive the initial focus</param>
private void FocusAndSelectItem(int itemIndex)
{
Dispatcher.BeginInvoke(new FocusAndSelectItemDelegate(TryFocusAndSelectItem), DispatcherPriority.ApplicationIdle, itemIndex);
}

/// <summary>
/// Make sure a list view item is within the visible area of the list view
/// and then select and set focus to it.
/// </summary>
/// <param name="itemIndex">index of item</param>
private void TryFocusAndSelectItem(int itemIndex)
{
ListViewItem lvi = myListView.Items.GetItemAt(itemIndex) as ListViewItem;
if (lvi != null)
{
myListView.ScrollIntoView(lvi);
lvi.IsSelected = true;
Keyboard.Focus(lvi);
}
}

private delegate void FocusAndSelectItemDelegate(int itemIndex);

 

That’s it. Hope this helps.

-Tan

Comments