[英]WPF - Selected Row is not changed after changing the day in a Datepicker control and pressing ENTER
我在DataGrid中使用Datepicker控件。 更改日期并按ENTER键之后,“选定的”行将保留在同一Datagrid行中,并且不会更改为下一个Datagrid行。 以下是我的DatePicker控件:
<DataGridTemplateColumn x:Name="startDateColumn" Width="*" Header="Start Date">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding StartDate, StringFormat=d}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding StartDate...
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
我想允许用户在选择一天并按Enter之后移动到下一个Datagrid行。
我怎样才能做到这一点?
提前致谢...
添加此附加属性类
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;
var parent = GetVisualParent<DataGrid>(ue);
if (parent == null) return;
if (e.Key == Key.Enter)
{
e.Handled = true;
ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
parent.SelectedIndex += 1;
}
}
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;
}
}
public static T GetVisualParent<T>(DependencyObject child) where T : Visual
{
Visual parentObject = VisualTreeHelper.GetParent(child) as Visual;
if (parentObject == null) return null;
return parentObject is T ? parentObject as T : GetVisualParent<T>(parentObject);
}
}
为DatePickerTextBox添加样式
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="local:EnterKeyTraversal.IsEnabled" Value="True"/>
</Style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.