关注 DataTemplate 中的文本框 [英] Focus on a TextBox in a DataTemplate
问题描述
我有包含 TextBox
的 DataTemplate
.我正在将此模板设置为所选内容的列表框项.
I have DataTemplate
containing a TextBox
. I'm setting this template to a listbox item on a selection.
我无法将焦点设置到模板中的文本框.我尝试调用 MyTemplate.FindName,但它以无效操作异常结束:此操作仅对应用了此模板的元素有效.
I'm unable to set focus to textbox in the template. I tried to call MyTemplate.FindName, but it ends up with an Invalid Operation Exception: This operation is valid only on elements that have this template applied.
如何访问它?
推荐答案
既然你知道你要关注的TextBox
的名字,这就变得相对容易了.这个想法是在模板应用于 ListBoxItem
本身时获取模板.
Since you know the name of the TextBox
you want to focus, this becomes relatively easy. The idea is to get hold of the template as it's applied to the ListBoxItem
itself.
您要做的第一件事是获取所选项目:
First thing you want to do is get the selected item:
var item = listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem) as ListBoxItem;
然后你可以将它传递给这个小助手函数,它会根据控件的名称来关注控件:
Then you can pass that into this little helper function which focuses a control based on its name:
public void FocusItem(ListBoxItem item, string name)
{
if (!item.IsLoaded)
{
// wait for the item to load so we can find the control to focus
RoutedEventHandler onload = null;
onload = delegate
{
item.Loaded -= onload;
FocusItem(item, name);
};
item.Loaded += onload;
return;
}
try
{
var myTemplate = FindResource("MyTemplateKey") as FrameworkTemplate; // or however you get your template right now
var ctl = myTemplate.FindName(name, item) as FrameworkElement;
ctl.Focus();
}
catch
{
// focus something else if the template/item wasn't found?
}
}
我想棘手的一点是确保您等待项目加载.我必须添加该代码,因为我是从 ItemContainerGenerator.StatusChanged
事件中调用它的,有时在我们进入该方法时 ListBoxItem
尚未完全初始化.
I guess the tricky bit is making sure you wait for the item to load. I had to add that code because I was calling this from the ItemContainerGenerator.StatusChanged
event and sometimes the ListBoxItem
hadn't been fully initialized by the time we entered the method.
这篇关于关注 DataTemplate 中的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!