You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# WPF .NET 4.8中实现带自动完成及联动填充的DataGrid

在WPF .NET 4.8中实现带自动完成与自动填充的DataGrid

1. 准备依赖与数据模型

WPF原生无内置自动完成控件,需通过NuGet安装WPFToolkit包。

先定义两个数据模型:一个存储第一列的可选数据源及对应填充字段,另一个作为DataGrid行的数据载体:

public class ProductInfo
{
    public string ProductName { get; set; }
    public string Category { get; set; }
    public string Specification { get; set; }
}

public class GridRowData
{
    public ProductInfo SelectedProduct { get; set; }
    public string Category { get; set; }
    public string Specification { get; set; }
    public string Quantity { get; set; }
    public string Remark { get; set; }
}

2. XAML布局实现

在Window/UserControl中定义DataGrid,第一列用DataGridTemplateColumn嵌入AutoCompleteBox,其余列绑定对应属性:

<Window x:Class="WpfDataGridDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
        Title="DataGrid Demo" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="mainDataGrid" 
                  ItemsSource="{Binding GridRows}"
                  AutoGenerateColumns="False"
                  CanUserAddRows="True"
                  SelectionUnit="CellOrRowHeader">
            <DataGrid.Columns>
                <!-- 第一列:带过滤的自动完成列 -->
                <DataGridTemplateColumn Header="产品名称" Width="200">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding SelectedProduct.ProductName}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <toolkit:AutoCompleteBox x:Name="productAutoComplete"
                                                     ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ProductList}"
                                                     DisplayMemberPath="ProductName"
                                                     FilterMode="Contains"
                                                     IsTextCompletionEnabled="True"
                                                     SelectionChanged="ProductAutoComplete_SelectionChanged"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
                <!-- 第二列:自动填充类别 -->
                <DataGridTextColumn Header="类别" Binding="{Binding Category}" IsReadOnly="True" Width="120"/>
                <!-- 第三列:自动填充规格 -->
                <DataGridTextColumn Header="规格" Binding="{Binding Specification}" IsReadOnly="True" Width="120"/>
                <!-- 第四列:手动输入数量 -->
                <DataGridTextColumn Header="数量" Binding="{Binding Quantity}" Width="100"/>
                <!-- 第五列:备注 -->
                <DataGridTextColumn Header="备注" Binding="{Binding Remark}" Width="*"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

3. 后台逻辑实现

在代码-behind中初始化数据源,处理自动完成选中事件,完成自动填充与光标跳转:

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Windows.Controls;

namespace WpfDataGridDemo
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<GridRowData> GridRows { get; set; }
        public ObservableCollection<ProductInfo> ProductList { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            // 初始化产品数据源
            ProductList = new ObservableCollection<ProductInfo>
            {
                new ProductInfo { ProductName = "笔记本电脑", Category = "电子产品", Specification = "15.6英寸" },
                new ProductInfo { ProductName = "无线鼠标", Category = "电子产品", Specification = "蓝牙5.0" },
                new ProductInfo { ProductName = "办公椅", Category = "办公家具", Specification = "人体工学" }
            };
            // 初始化DataGrid行数据
            GridRows = new ObservableCollection<GridRowData>();
            DataContext = this;
        }

        private void ProductAutoComplete_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var autoCompleteBox = sender as AutoCompleteBox;
            if (autoCompleteBox?.SelectedItem is ProductInfo selectedProduct)
            {
                // 获取当前编辑行数据并填充第二、三列
                var rowData = autoCompleteBox.DataContext as GridRowData;
                if (rowData != null)
                {
                    rowData.SelectedProduct = selectedProduct;
                    rowData.Category = selectedProduct.Category;
                    rowData.Specification = selectedProduct.Specification;
                }

                // 跳转到第四列并进入编辑状态
                var row = mainDataGrid.CurrentCell.Item as GridRowData;
                if (row != null)
                {
                    var quantityColumn = mainDataGrid.Columns[3];
                    mainDataGrid.CurrentCell = new DataGridCellInfo(row, quantityColumn);
                    mainDataGrid.BeginEdit();

                    // 聚焦到第四列输入框
                    if (mainDataGrid.ItemContainerGenerator.ContainerFromItem(row) is DataGridRow dataGridRow)
                    {
                        dataGridRow.BringIntoView();
                        if (dataGridRow.ItemContainerGenerator.ContainerFromIndex(3) is DataGridCell cell && cell.Content is TextBox textBox)
                        {
                            textBox.Focus();
                            textBox.SelectAll();
                        }
                    }
                }
            }
        }
    }
}

关键细节说明

  • 自动过滤:通过AutoCompleteBox的FilterMode="Contains"实现输入时模糊匹配,IsTextCompletionEnabled="True"开启文本补全。
  • 自动填充:在选中事件中直接将选中产品的对应字段赋值给当前行的Category和Specification属性。
  • 光标跳转:通过切换CurrentCell定位到第四列,调用BeginEdit()进入编辑模式,再找到对应单元格的TextBox并聚焦。

内容的提问来源于stack exchange,提问作者user3506644

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 15:44:52