WPF Datagrid列以编程方式选择时不打开编辑模式

时间:2018-04-01 03:22:18

标签: c# wpf

我在wpf中有一个Datagrid,如下所示:

 <DataGrid Grid.Row="1" Grid.Column="1" x:Name="GridItems" HorizontalAlignment="Stretch" Margin="1" Background="Transparent" VerticalAlignment="Stretch"
                  AutoGenerateColumns="False"  GridLinesVisibility="All" HeadersVisibility="Column" SelectionMode="Single" SelectionUnit="Cell" 
                   VerticalContentAlignment="Center" SelectedIndex="-1" CanUserAddRows="False" ItemsSource="{Binding Transaction.TransactionItems}"
                   VerticalGridLinesBrush="#ccc" HorizontalGridLinesBrush="#ccc" AlternationCount="2" AlternatingRowBackground="#F2F2F2" 
                   BorderThickness="0" RowHeaderWidth="0"  CellStyle="{StaticResource CellStyleWithPadding}" 
                   CellEditEnding="GridItems_CellEditEnding_1" PreviewKeyDown="GridItems_PreviewKeyDown_1" MouseDoubleClick="GridItems_MouseDoubleClick" BeginningEdit="GridItems_BeginningEdit">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="Id" Visibility="Collapsed" Binding="{Binding Id}"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="Code" Header="Code" Width="50" Binding="{Binding Code,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="Name" Header="Name" Width="*" Binding="{Binding Name}" IsReadOnly="True"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="Unit" Header="Unit" Width="40" Binding="{Binding SelectedUnit.Name}" IsReadOnly="True" Visibility="Collapsed"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="SalePrice" Header="Sale Price" IsReadOnly="True" Width="70" Binding="{Binding SalePrice,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ElementStyle="{StaticResource RightCell}"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="Quantity"  Header="Quantity" Width="70" Binding="{Binding Quantity,Mode=TwoWay,UpdateSourceTrigger=LostFocus}" ElementStyle="{StaticResource RightCell}"></DataGridTextColumn>
                    <DataGridTextColumn x:Name="Amount"  Header="Amount" Width="80" Binding="{Binding Amount}" ElementStyle="{StaticResource RightCell}" IsReadOnly="True"></DataGridTextColumn>
                    <DataGridTemplateColumn Width="60" Header="Remove">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button x:Name="BtnDelete" Click="BtnDelete_Click_1" Background="Transparent" BorderThickness="0">
                                    <Image Height="25" Source="/Images/delete.png"/>
                                </Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>

在此网格中,只有代码和数量是可编辑的,并且我使用代码将焦点直接设置为从代码开始的数量,然后从数量到下一行代码列。设置焦点代码如下:

   public static void SelectCellByIndex(this DataGrid dataGrid, int rowIndex, int columnIndex)
        {
            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.Cell))
                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to Cell.");

            if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
                return;

            if (columnIndex < 0 || columnIndex > (dataGrid.Columns.Count - 1))
                return;

            dataGrid.SelectedCells.Clear();

            object item = dataGrid.Items[rowIndex]; //=Product X
            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            if (row == null)
            {
                dataGrid.ScrollIntoView(item);
                row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            }
            if (row != null)
            {
                DataGridCell cell = GetCell(dataGrid, row, columnIndex);
                if (cell != null)
                {
                    DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(cell);
                    dataGrid.CurrentCell = dataGridCellInfo;
                    if (!dataGrid.SelectedCells.Contains(dataGridCellInfo))
                        dataGrid.SelectedCells.Add(dataGridCellInfo);
                    cell.Focus();
                    //TextBox ele = ((ContentPresenter)(cell.Column.GetCellContent(row))).Content as TextBox;
                    //ele.Focus();
                    //dataGrid.BeginEdit();
                }
            }
        }

        public static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
        {
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                if (presenter == null)
                {
                    /* if the row has been virtualized away, call its ApplyTemplate() method
                     * to build its visual tree in order for the DataGridCellsPresenter
                     * and the DataGridCells to be created */
                    rowContainer.ApplyTemplate();
                    presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                }
                if (presenter != null)
                {
                    DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    if (cell == null)
                    {
                        /* bring the column into view
                         * in case it has been virtualized away */
                        dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                        cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    }
                    return cell;
                }
            }
            return null;
        }

        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

现在这个代码工作正常,除了1个问题,当我将焦点设置到下一列,然后当我按任意键时它不会进入编辑模式。我也使用了DataGrid.BeginEdit但是当我使用它然后CellEditEnding是不会被那个列/单元格解雇。

有人可以帮助我吗?

0 个答案:

没有答案