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

VB.NET MVVM WPF中DataGrid绑定DataTable失败求助

问题解决步骤

1. 修复ViewModel属性的赋值错误

你的dtCharDG属性在Set方法里没有正确更新私有字段,且参数名不符合VB.NET规范,这会导致UI永远获取不到新的DataView。修改后的属性代码如下:

Private dtCharDGValue As DataView

Public Property dtCharDG() As DataView
    Get
        Return dtCharDGValue
    End Get
    Set(value As DataView)
        ' 先更新私有字段
        dtCharDGValue = value
        ' 再通知UI更新
        NotifyPropertyChanged()
    End Set
End Property

2. 完善DataTable的创建逻辑

原CreateCharGrid方法只添加了位置序号的行,缺少字符行,且列未命名(虽不影响功能,但可读性差)。修改后满足你“首行显示位置、第二行显示字符”的需求:

Public Sub CreateCharGrid(ByVal CharSet As String, ByRef dtToFill As DataTable)
    Dim x As Integer = CharSet.Length
    Dim workColumn As DataColumn
    Dim workRow As DataRow

    ' 创建列并命名(用位置序号作为列名)
    For y As Integer = 0 To x - 1
        workColumn = New DataColumn($"Pos_{y + 1}") ' 列名示例:Pos_1、Pos_2
        dtToFill.Columns.Add(workColumn)
    Next

    ' 第一行:添加位置序号
    workRow = dtToFill.NewRow()
    For y As Integer = 0 To x - 1
        workRow(y) = y + 1
    Next
    dtToFill.Rows.Add(workRow)

    ' 第二行:添加对应字符
    workRow = dtToFill.NewRow()
    For y As Integer = 0 To x - 1
        workRow(y) = CharSet(y)
    Next
    dtToFill.Rows.Add(workRow)
End Sub

3. 调整DataGrid绑定(可选优化)

DataView的绑定不需要TwoWay模式(引用类型绑定无需双向同步),可简化绑定代码:

<DataGrid ItemsSource="{Binding dtCharDG}" AutoGenerateColumns="True" Margin="0,152,0,251" />

问题根源说明

  • 核心错误:ViewModel属性的Set方法未更新私有字段,导致UI绑定的始终是初始null值,DataGrid无数据可显示。
  • 逻辑缺失:原方法仅添加了位置行,未添加字符行,即使绑定正常也无法达成目标效果。

按以上步骤修改后,点击按钮即可看到首行显示位置序号、第二行显示对应字符的DataGrid。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:30:17