当datagrid-cell获得焦点时自动编辑WPF数据网格内容

时间:2015-01-27 10:48:39

标签: c# wpf xaml datagrid

我在WPF中有一个带有 DataGridTextColum DataGridTemplateColum 的数据网格。

<DataGridTextColumn Width="4*" IsReadOnly="True" x:Name="dataGridColumnDescription" 
Header="Description" Binding="{Binding Description}">
</DataGridTextColumn>

<DataGridTemplateColumn CellStyle="{StaticResource CellEditing}" IsReadOnly="False" Width="*" Header="Value" 
CellEditingTemplateSelector="{StaticResource myCellEditingTemplateSelectorValue}" 
CellTemplateSelector="{StaticResource myCellTemplateSelectorValue}">
</DataGridTemplateColumn>

CellTemplateSelectors返回带有TextBlock的DataTemplate,用于Celltemplate resp。用于CellEditing的TextBox!

<DataTemplate x:Key="dGridStringValueTemplate">
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=Value}"/>
</DataTemplate>

<DataTemplate x:Key="dGridStringValueTemplateEditing">
    <TextBox TextAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" BorderThickness="1" Text="{Binding Path=Value, UpdateSourceTrigger=LostFocus}"/>
</DataTemplate>

现在我想在DataGridCell获得焦点时自动聚焦TextBox。用户应该能够在不双击单元格的情况下编辑TextBox内容。

我找到了这篇文章:

DataGrid Tips & Tricks: Single-Click Editing 我可以在哪里获得Current DataGridCell,但是如何访问内容以使Textbox成为编辑内容的焦点?

这是我的风格:

<Style x:Key="CellEditing" TargetType="{x:Type DataGridCell}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="myDataGridMain_PreviewMouseLeftButtonDown"></EventSetter>
</Style>

这是我的事件处理程序:

private void myDataGridMain_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    DataGridCell cell = sender as DataGridCell;     // cell ist not null

    DataGridTemplateColumn col = cell.Column as DataGridTemplateColumn; //col is not null

    DataTemplate template = col.CellTemplate;  //this is null
}

如何使用该事件处理程序获取文本框?

4 个答案:

答案 0 :(得分:15)

这似乎有效:

    <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <TextBox  FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

答案 1 :(得分:2)

我管理它,不是最好的解决方案,但它有效...... 当Cell获得焦点时,我将其设置为编辑模式。

private void myDataGridMain_OnFocus(object sender, RoutedEventArgs e)
{
    DataGridCell cell = sender as DataGridCell;
    if (cell != null)
        cell.IsEditing = true;
    //var test = FindVisualChild<TextBlock>(cell);
}

On Keydown我搜索视觉孩子并给予焦点。

private void myDataGridMain_KeyDown(object sender, KeyEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;

            if (e.Key == Key.Enter)
            {   //give cell the focus
                cell.Focus();
            }
            else
            {
                if ((cell != null))
                {
                    TextBox textbox = FindVisualChild<TextBox>(cell);
                    if (textbox != null)
                    {   //TextBox has benn found
                        if ((textbox as TextBox).IsFocused == false)
                        {
                            (textbox as TextBox).SelectAll();
                        }
                        (textbox as TextBox).Focus();
                    }

                    CheckBox chkbox = FindVisualChild<CheckBox>(cell);
                    if (chkbox != null)
                    {   //Checkbox has been found
                        (chkbox as CheckBox).Focus();
                    }

                    ComboBox combbox = FindVisualChild<ComboBox>(cell);
                    if (combbox != null)
                    {   //ComboBox has been found
                        (combbox as ComboBox).Focus();
                    }
                }
            }
        }

寻找视觉孩子!

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;
}

答案 2 :(得分:0)

这种方法适合我。它使用以下事实:DataGrid将始终在编辑开始时创建模板的新实例:

<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <TextBox Text="{Binding MyProperty}" 
                 Loaded="TextBox_Loaded"></TextBox>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

并在后面的代码中:

private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
    ((TextBox)sender).Focus();
    ((TextBox)sender).SelectAll();
}

作为额外奖励,它还会选择单元格中的所有文本。无论你如何进入编辑模式(双击,单击,按F2),它都应该有效。

答案 3 :(得分:0)

这个简单的答案创建了从数据网格控件派生的新控件

  using System.Windows.Controls;

   public class CustomDataGrid : DataGrid
   {

    protected override void OnSelectedCellsChanged(SelectedCellsChangedEventArgs e)
    {
        //to make sure cell is selected
        var cells = e.AddedCells.FirstOrDefault();
        if (cells != null)
        {
            this.BeginEdit();

        }
        base.OnSelectedCellsChanged(e);
    }

   }
相关问题