【问题标题】:how to set focus to particular cell of WPF toolkit datagrid如何将焦点设置到 WPF 工具包数据网格的特定单元格
【发布时间】:2011-03-26 04:42:33
【问题描述】:

我正在使用 WPF 工具包提供的 DataGrid 控件来显示产品列表及其 OpenStock、描述等。在此 DataGrid 中,我已将 OpenStock 列设置为可编辑,其余列不可编辑。我现在想要什么,当我的这个窗口加载时,我想将键盘焦点设置到 OpenStock 列的第一个单元格,如果可能的话,在编辑模式下。我搜索了 2 天,最后在这里发布。

任何帮助或代码示例都会有所帮助。

<my:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="2,2,2,55" 
x:Name="dataGrid1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="White"    
AlternatingRowBackground="AliceBlue" AlternationCount="2" SelectionMode="Single" 
SelectionUnit="Cell" BorderThickness="0" IsTabStop="True">
        <my:DataGrid.Resources>
            <Style x:Key="errorStyle" TargetType="{x:Type TextBox}">
                <Setter Property="Padding" Value="-2"/>
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="Background" Value="Yellow"/>
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                                Path=(Validation.Errors)[0].ErrorContent}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </my:DataGrid.Resources>
        <my:DataGrid.Columns>
            <my:DataGridTextColumn Width="60" FocusManager.IsFocusScope="False" Binding="{Binding Path=pCode}" Header="Code" IsReadOnly="True" />
            <my:DataGridTextColumn Width="150" Binding="{Binding pName}" Header="Description"  IsReadOnly="True" />
            <my:DataGridTextColumn Width="120" Binding="{Binding CloseStock}" Header="Closing Stock"  IsReadOnly="True" />
            <my:DataGridTextColumn  Width="100" Binding="{Binding OpenStock, ValidatesOnExceptions=True}" Header="Open Stock"
                                   EditingElementStyle="{StaticResource errorStyle}"/>
            <my:DataGridTextColumn Width="150" Binding="{Binding YrlyOpenStock}" Header="Yearly Opening"  IsReadOnly="True" />

        </my:DataGrid.Columns>
    </my:DataGrid>       

非常感谢........

【问题讨论】:

    标签: c# wpf wpfdatagrid


    【解决方案1】:

    您需要将当前单元格设置为您要编辑的单元格,然后在 Loaded 处理程序中调用 BeginEdit:

    dataGrid1.CurrentCell = new DataGridCellInfo(
        dataGrid1.Items[0], dataGrid1.Columns[3]);
    dataGrid1.BeginEdit();
    

    如果您在 XAML 中为 DataGridTextColumn 指定一个名称,则可以使用该名称而不是 Columns[3]。

    【讨论】:

    • 很好的答案。我必须将焦点设置在 dataGrid“dataGrid1.Focus();”上首先但后来它起作用了。
    • 请注意dataGrid1.Columns集合中的列顺序不一定是屏幕上显示的顺序,请参阅msdn.microsoft.com/en-us/library/…中的注释。如果您确实需要按显示顺序进行索引,只需将dataGrid1.Columns.OrderBy(c =&gt; c.DisplayIndex).ToArray() 存储在局部变量中,然后索引到该数组中即可。
    【解决方案2】:

    使用此代码将滚动视图移动到特定单元格:

    dgv.ScrollIntoView(dgv.Items[row], dgv.Columns[col]);
    

    【讨论】:

      【解决方案3】:

      使用下面的函数,它会起作用的。

      private void SetFocusOnGrid(DataGrid grid, int index)
      {
          grid.ScrollIntoView(grid.Items.GetItemAt(index));
          grid.SelectionMode = DataGridSelectionMode.Single;
          grid.SelectionUnit = DataGridSelectionUnit.FullRow;
          grid.SelectedIndex = index;
      
          DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
          row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
      }  
      

      【讨论】:

        【解决方案4】:

        这对我有用:

        DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(dataGrid1.Items[sampleRowIndex], dataGrid1.Columns[sampleColumnIndex]);
        dataGrid1.SelectedCells.Clear();
        dataGrid1.SelectedCells.Add(dataGridCellInfo);
        

        这将选择您要聚焦的单元格。

        DataGridCellInfo 对象提供有关单元格和与该单元格关联的数据项的信息。当 DataGrid 控件获取单元格时(例如在 CurrentCell 或 SelectedCells 属性中),使用它代替对实际 DataGridCell 对象的引用。更多信息请查看here。

        【讨论】:

          【解决方案5】:

          我在 DataGridTemplateColumn 的 DataTemplate 中有带有 TextBox 的数据网格。 我也使用 Enter 而不是 Tab 来聚焦 TextBox

          private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
          {
              if (e.Key == Key.Enter)
              {
                  e.Handled = true;
                  var TabKey = new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, Key.Tab);
                  TabKey.RoutedEvent = Keyboard.KeyDownEvent;
                  InputManager.Current.ProcessInput(TabKey);
              }
          }
          

          我用这段代码的组合解决了焦点问题:

          dataGrid.Focus();
          //In case of more columns
          //dataGrid.CurrentCell = new DataGridCellInfo(dataGrid.Items[0], dataGrid.Columns[1]);
          dataGrid.BeginEdit();
          (Keyboard.FocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-01-29
            • 1970-01-01
            • 1970-01-01
            • 2010-12-02
            • 2015-05-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多