焦点到行选择上的 wpf 数据网格中的特定可编辑数据网格单元格



我在数据网格中有四列,第四列是模板化的,并且具有始终可编辑的文本框。

我在这里要实现的是,当行选择更改突出显示行的第四个单元格时,该单元格是可编辑的并且其中包含文本框应该获得焦点。

我可以在代码隐藏或 xaml 中完成此操作。

这是我所做的:

<DataGrid Name="MyGrid" SelectionChanged="MyGrid_OnSelectionChanged" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Str1}" IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Str2}" IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Str3}" IsReadOnly="True"/>
            <DataGridTemplateColumn >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Str4}" GotFocus="UIElement_OnGotFocus" >
                            <TextBox.Style >
                                <Style TargetType="TextBox">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell,AncestorLevel=1},Path=IsSelected}">
                                            <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBox.Style>
                        </TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
private void PopulateDummies()
    {
        int i = 0;
        List<SomeDummy> dummies = new List<SomeDummy>();
        while (i < 10)
        {
            dummies.Add(new SomeDummy
            {
                Str1 = string.Format("Str1:{0}", i),
                Str2 = string.Format("Str2:{0}", i),
                Str3 = string.Format("Str3:{0}", i),
                Str4 = string.Format("Str4:{0}", i)
            });
            i++;
        }
        MyGrid.ItemsSource = dummies;
    }
    private void MyGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    }
    private void UIElement_OnGotFocus(object sender, RoutedEventArgs e)
    {
        var txtB = sender as TextBox;
        txtB.Focus();
        txtB.SelectAll();
    }

似乎什么都不起作用。不知道是什么原因。谁能帮忙

语句

txtB.Focus();

有效地将 DataGridCell 替换为 TextEditory 控件。为此,需要更新视图,因此需要运行 UI 踏板。在创建编辑器之前,SelectAll 无法运行,因此请将其作为单独的调度程序作业运行,并将其替换为以下内容:

Application.Current.Dispatcher.BeginInvoke(new Action(() => { 
    txtB.SelectAll();
}), DispatcherPriority.Render);

这将解决问题,并且您不需要SelctionChanged事件处理程序来实现此目的。

最新更新