WPF. How to set focus on an element by it's tab index?
Is it possible to get an element or set focus on it (Te开发者_C百科xtBox, for instance) by it's tab index, if the element is a part of a DataTemplate and the tab index of the element is uniquely defined?
You can VisualTreeHelper for search any element that is created through templates.
Therefore you can check the TabIndex of any existing element and will find your desired element (it your tab-index is really unique:). You can also name your elments in the DataTemplate and the filter for the name.
The following function lets you find all elements of a given type of the visual tree.
void FindChildFrameworkElementsOfType<T>(DependencyObject parent,IList<T> list) where T: FrameworkElement{
DependencyObject child;
for(int i=0;i< VisualTreeHelper.GetChildrenCount(parent);i++){
child = VisualTreeHelper.GetChild(parent, i);
if (child is T) {
list.Add((T)child);
}
FindChildFrameworkElementsOfType<T>(child,list);
}
}
Call it as follows:
List<TextBox> textBoxList=new List<TextBox>();
FindChildFrameworkElementsOfType<TextBox>(rootObject,textBoxList);
Where rootObject
is the root object such as your window or the base control. You will get a list of all textboxes and this list can the checked for the tab-index or whatever property you want to check.
Take care that the tree must be built before calling this function. Als there are some circumstances in which the above pattern does not work, e.g. with UI-virtualization in lists.
精彩评论