Я использую 2 куска кода для этого.C #, но вы должны быть в состоянии запустить его через онлайн-конвертер.Один отображает выбранную строку, а другой фокусирует ее.
Я забыл, откуда именно они произошли - я уже давно их использую.
class ScrollDataGridRowIntoView : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is DataGrid)
{
DataGrid datagrid = (sender as DataGrid);
if (datagrid.SelectedItem != null)
{
datagrid.Dispatcher.BeginInvoke((Action)(() =>
{
datagrid.UpdateLayout();
if (datagrid.SelectedItem != null)
{
datagrid.ScrollIntoView(datagrid.SelectedItem);
}
}));
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
}
}
и
class DataGridRowFocusBehavior : Behavior<DataGridRow>
{
public static bool GetIsDataGridRowFocussedWhenSelected(DataGridRow dataGridRow)
{
return (bool)dataGridRow.GetValue(IsDataGridRowFocussedWhenSelectedProperty);
}
public static void SetIsDataGridRowFocussedWhenSelected(
DataGridRow dataGridRow, bool value)
{
dataGridRow.SetValue(IsDataGridRowFocussedWhenSelectedProperty, value);
}
public static readonly DependencyProperty IsDataGridRowFocussedWhenSelectedProperty =
DependencyProperty.RegisterAttached(
"IsDataGridRowFocussedWhenSelected",
typeof(bool),
typeof(DataGridRowFocusBehavior),
new UIPropertyMetadata(false, OnIsDataGridRowFocussedWhenSelectedChanged));
static void OnIsDataGridRowFocussedWhenSelectedChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
DataGridRow item = depObj as DataGridRow;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
item.Selected += OndataGridRowSelected;
else
item.Selected -= OndataGridRowSelected;
}
static void OndataGridRowSelected(object sender, RoutedEventArgs e)
{
DataGridRow row = e.OriginalSource as DataGridRow;
// If focus is already on a cell then don't focus back out of it
if (!(Keyboard.FocusedElement is DataGridCell) && row != null)
{
row.Focusable = true;
Keyboard.Focus(row);
}
}
}
В моей таблице данных:
<i:Interaction.Behaviors>
<local:ScrollDataGridRowIntoView />
</i:Interaction.Behaviors>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="local:DataGridRowBehavior.IsDataGridRowFocussedWhenSelected" Value="true"/>
</Style>
</DataGrid.RowStyle>
xmlns для i:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"