我有一个Datagrid
,DataGridTemplateColumn
,其中有一个TextBox
。当焦点在文本框中时,我按回车键转到下一条记录,它会关注DataGridTemplateColumn
而不是子文本框,迫使我按Tab
进入文本框。我发现这个代码可以使用Tab键进入工作量很大的列,但是当我按Enter键时我无法获得相同的功能。
<Style x:Key="columnTabStop" TargetType="{x:Type DataGridCell}">
<Setter Property="KeyboardNavigation.IsTabStop" Value="False" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="KeyboardNavigation.IsTabStop" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
这是我的DataGridTemplateColumn
代码:
<DataGridTemplateColumn Header="Weld Time" CellStyle="{StaticResource columnTabStop}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.WeldTime,RelativeSource={RelativeSource AncestorType=DataGridRow}}"
BorderThickness="0" BorderBrush="Transparent" Background="BlanchedAlmond" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我已尝试停用Focusable
和IsHitTestVisible
但这些不是我需要的。我还玩过其他几个KeyboardNavigation
设置,但还没有让它工作。必须有一种实现这一目标的方法,但我没有找到任何运气。基本上我想绕过DataGridTemplateColumn
完全只允许焦点到子控件。这可能吗?
答案 0 :(得分:1)
添加此附加属性类
public class EnterKeyTraversal
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void ue_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
var ue = e.OriginalSource as FrameworkElement;
if (e.Key == Key.Enter)
{
e.Handled = true;
ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
private static void ue_Unloaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null) return;
ue.Unloaded -= ue_Unloaded;
ue.PreviewKeyDown -= ue_PreviewKeyDown;
}
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
typeof(EnterKeyTraversal), new UIPropertyMetadata(false, IsEnabledChanged));
static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ue = d as FrameworkElement;
if (ue == null) return;
if ((bool)e.NewValue)
{
ue.Unloaded += ue_Unloaded;
ue.PreviewKeyDown += ue_PreviewKeyDown;
}
else
{
ue.PreviewKeyDown -= ue_PreviewKeyDown;
}
}
}
并设置DataGridCell的样式
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="local:EnterKeyTraversal.IsEnabled" Value="True"/>
</Style>