在我的视图中有一个ItemsControl,它绑定到ViewModel的ObservableCollection。该集合已被填充,之后将引发从VM到视图的事件(想想搜索结果和SearchFinished事件)。 如何将键盘焦点移动到ItemsControl中的第一项? 我正在使用MVVM模式
答案 0 :(得分:0)
我在使用行为之前完成了这项工作:
public sealed class FocusBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += OnLoaded;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
AssociatedObject.Focus();
}
}
然后在XAML中使用它,如下所示:
<TextBox x:Name="UsernameTextBox"
Text="{Binding Path=Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
KeyboardNavigation.TabIndex="0">
<i:Interaction.Behaviors>
<b:FocusBehavior />
</i:Interaction.Behaviors>
</TextBox>
您需要引用System.Windows.Interactivity程序集以引入Interaction名称空间。
答案 1 :(得分:0)
我找到了解决方案..
private void VerifiValue_Loaded(object sender, RoutedEventArgs e)
{
if (verificationIC.Items.Count > 0)
{
UIElement uiElement = (UIElement)verificationIC.ItemContainerGenerator.ContainerFromIndex(0);
TextBox t = GetChild<TextBox>(uiElement);
t.Focus();
t.SelectAll();
}
}
public T GetChild<T>(DependencyObject obj) where T : DependencyObject
{
DependencyObject child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child.GetType() == typeof(T))
{
break;
}
else if (child != null)
{
child = GetChild<T>(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
}
}
return child as T;
}