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

在WPF DataGrid中托管WinForms TextBox的绑定实现问题

解决WPF DataGrid中WinForms TextBox的数据绑定问题

因为WinForms控件不支持WPF的XAML绑定语法,你需要通过代码创建WinForms原生的数据绑定来实现。以下是具体的实现步骤:

1. 引用必要程序集

确保项目已引用:

  • System.Windows.Forms
  • WindowsFormsIntegration

2. XAML中定义DataGrid列(包含WindowsFormsHost)

在DataGrid的列集合里添加DataGridTemplateColumn,模板中放入WindowsFormsHost并承载WinForms TextBox:

<DataGrid x:Name="MyDataGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <!-- 其他列 -->
        <DataGridTemplateColumn Header="WinForms文本框">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <WindowsFormsHost Loaded="WinFormsTextBoxHost_Loaded">
                        <wf:TextBox x:Name="WinFormsTxtBox" />
                    </WindowsFormsHost>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

注意:需要在XAML根节点添加命名空间映射:xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

3. VB.NET后台代码实现绑定

在WindowsFormsHost的Loaded事件中,获取当前行的DataRowView,并为WinForms TextBox创建WinForms原生的Binding:

Private Sub WinFormsTextBoxHost_Loaded(sender As Object, e As RoutedEventArgs)
    ' 获取当前WindowsFormsHost控件
    Dim host = DirectCast(sender, WindowsFormsHost)
    ' 获取内部的WinForms TextBox
    Dim winFormsTxt = DirectCast(host.Child, TextBox)
    ' 获取当前行的数据上下文(DataRowView,因为绑定的是DataTable)
    Dim rowView = DirectCast(host.DataContext, DataRowView)

    ' 创建WinForms的Binding,绑定到DataRowView的指定列(比如"name"列)
    ' 设置双向绑定,当文本框内容变化时自动更新DataTable
    Dim txtBinding = New Binding("Text") With {
        .DataSource = rowView,
        .DataMember = "name",
        .DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
    }

    ' 将绑定添加到TextBox的DataBindings集合
    winFormsTxt.DataBindings.Add(txtBinding)
End Sub

关于BindingContext的说明

WinForms的BindingContext主要用于管理多个数据源的绑定关系,在这个场景下不需要单独设置——因为我们直接通过DataRowView作为数据源创建Binding,WinForms控件会自动使用默认的BindingContext来维护绑定。只有当你需要在同一个控件上绑定多个不同数据源时,才需要手动配置BindingContext。

验证双向绑定

当你在WinForms TextBox中输入内容时,对应的DataTable行的"name"列会自动更新;反之,DataTable中数据变化时,TextBox的内容也会同步刷新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:05:50