简体   繁体   中英

Focus is not set in UserControl WPF

I cannot able to set focus on User Control Item I am using DataGrid in User Control I want to set focus on First row of DataGrid

I found following code

int index = 0;

dgAccountInfo.SelectedItem = winAccountInfoGrid.dgAccountInfo.Items[index];
dgAccountInfo.ScrollIntoView(winAccountInfoGrid.dgAccountInfo.Items[index]);

DataGridRow dgrow = (DataGridRow)dgAccountInfo.ItemContainerGenerator.ContainerFromIndex(index);

if (dgrow != null)
{
   dgAccountInfo.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next))
};

By running above code I found ContainerFromIndex method always returns null

To rid of null problem I found following link

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/ab95dd62-995f-481a-a765-d5efff1d559c/

I come out of null problem using above link but still focus is not set on data grid

Thanks for reading my question

It appears that, in the code you're using, you are data binding to something else, which is unnecessary if you are only wanting to set the focus to the first item. If your only intention is to set the focus (selected index) of the datagrid, that can be accomplished in one single block of code.

if (dgAccountInfo.HasItems){    
  dgAccountInfo.SelectedIndex = 0;
}

The if construct ensures that your datagrid actually has items in it (otherwise, the next line of code would throw an exception). If the datagrid has items, it executes the code inside the construct. If the datagrid has no items, it skips right over the code.

Even if you never plan to have no items in your datagrid, you should include this if construct anyway, in the off chance that something does happen

Inside the if construct, you set the datagrid's SelectedIndex to the first item. Remember that, like with a list box, a datagrid is "zero-based," meaning that the first item has an index of zero. To select nothing in the datagrid, set the selected index to "-1"

In the end, setting "SelectedIndex" is far more reliable than setting "SelectedItem," as the items in a datagrid usually change.

If you wanted, you could include an #else statement in the above code (just above endif) if you wanted to do something else if the datagrid has no items.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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