[英]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.