Можете ли вы получить объект сетки данных только с помощью DataGridRow? WPF - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь получить сетку данных, потому что хочу сфокусироваться на определенной c строке подряд. У меня есть DataGridRow, основанный на событии LoadingRow, которое я использую, выполняя это:

<i:EventTrigger EventName="LoadingRow">
   <utils:InteractiveCommand Command="{Binding RelativeSource = {RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowViewModel.SDataGrid_LoadingRow}"/>
</i:EventTrigger>

Но в функции, получающей это, я могу получить только DataGridRow.

    public void SDataGridLoadingRow(object param)
    {
        DataGridRowEventArgs e = param as DataGridRowEventArgs;
        e.Row.Tag = e.Row.GetIndex().ToString();
    }

Я хочу получить указанную c ячейку из строки и сфокусироваться на ней, чтобы пользователь мог печатать. Это возможно?

Я использую MVVM

Также есть это сейчас

    public void SDataGridLoadingRow(object sender, DataGridRowEventArgs e)
    {
        e.Row.Tag = e.Row.GetIndex().ToString();

        DataGrid dataGrid = sender as DataGrid;
        dataGrid.Focus();

        // Cancel our focus from the current cell of the datagrid
        // if there is a current cell
        if (dataGrid.CurrentCell != null)
        {
            var cancelEdit = new System.Action(() =>
            {
                dataGrid.CancelEdit();
            });
            Application.Current.Dispatcher.BeginInvoke(cancelEdit,
                System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
        }

        dataGrid.CurrentCell = new DataGridCellInfo(
            dataGrid.Items[e.Row.GetIndex()], dataGrid.Columns[1]);

        var startEdit = new System.Action(() =>
        {
            dataGrid.BeginEdit();
        });
        Application.Current.Dispatcher.BeginInvoke(startEdit, 
            System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
    }

И предыдущая строка все еще находится в режиме редактирования ... не могу выяснить, как вывести его из режима редактирования ...

1 Ответ

0 голосов
/ 02 мая 2020

Я не уверен, почему ваш обработчик события LoadingRow находится в вашей ViewModel. Если вы используете MVVM, ваши viewModels не должны манипулировать визуальными элементами, такими как DataGrid и DataGridCell, а только базовыми бизнес-данными.

В вашем случае вы можете подписаться на событие LoadingRow, например:

<DataGrid ItemsSource="{Binding BusinessObjectExemples}" LoadingRow="DataGrid_LoadingRow" />

и затем в вашем коде (файл xaml.cs):

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        if (sender is DataGrid dataGrid && e.Row is DataGridRow row)
        {
            //You can now access your dataGrid and the row
            row.Tag = row.GetIndex().ToString();
            //The grid is still loading row so it is too early to set the current cell.
        }
    }

Что вы можете сделать, это подписаться на загруженное событие вашей сетки и установить туда selectedCell:

private void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        //Adapt the logic for the cell you want to select
        var dataGridCellInfo = new DataGridCellInfo(this.Grid.Items[11], this.Grid.Columns[1]);
        //The grid must be focused in order to be directly editable once a cell is selected
        this.Grid.Focus();
        //Setting the SelectedCell might be neccessary to show the "Selected" visual
        this.Grid.SelectedCells.Clear();
        this.Grid.SelectedCells.Add(dataGridCellInfo);

        this.Grid.CurrentCell = dataGridCellInfo;
    }

Вы также можете выполнить ту же логику c с помощью кнопки.

Xaml:

<DataGrid x:Name="Grid" ItemsSource="{Binding BusinessObjectExemples}" 
                  Loaded="Grid_Loaded" SelectionUnit="Cell" AutoGenerateColumns="False" 
                  LoadingRow="DataGrid_LoadingRow">

А если какая-то часть обработки связана с бизнесом и должна быть в вашей viewModel. Затем вы можете вызвать команду или запустить publi c методы из DataGrid_LoadingRow в вашем коде позади.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...