WPF避免添加重复行

时间:2015-10-01 17:15:12

标签: wpf vb.net datagrid

我正在使用vb.net framework 4.5和WPF项目。

我有一个按钮,该功能会将某个产品信息添加到数据网格中。在我的vb代码文件中,我设置了一个产品类

Public Class MyProduct
    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemUnitPrice As Double
    Public Property ItemQty As Integer
End Class

按钮触地事件

Private Sub Button_TouchDown(sender As Object, e As TouchEventArgs)

        Dim dmb As New MyProduct
        dmb.ItemNumber = "abc001"
        dmb.ItemDescription = "bla bla bla"
        dmb.ItemQty = 1
        dmb.ItemUnitPrice = 123.45

        MyDataGrid.Items.Add(dmb)

End Sub

目前,如果我多次点击此按钮,数据网格将为同一产品添加多个重复行。我的目标是当多个相同的产品添加到datagrid时,只显示一行,并且同一按钮上的每个额外点击/单击操作只会增加ItemQty编号。

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您需要防止插入两次:

Private Sub buttonAdd_Click(sender As Object, e As RoutedEventArgs) Handles buttonAdd.Click
    Dim dmb As New MyProduct
    dmb.ItemNumber = New Random().Next(5).ToString()
    dmb.ItemDescription = "bla bla bla"
    dmb.ItemQty = 1
    dmb.ItemUnitPrice = 123.45

    Dim dmbSearched As MyProduct = Nothing
    For Each dmbs As MyProduct In MyDataGrid.Items
        If dmbs.ItemNumber = dmb.ItemNumber Then
            dmbSearched = dmbs
            Exit For
        End If
    Next

    If dmbSearched Is Nothing Then
        MyDataGrid.Items.Add(dmb)
    Else
        dmbSearched.ItemQty += 1
    End If
End Sub

其次,MyProduct类必须在数量发生变化时引发事件,否则没有明显的变化:

Public Class MyProduct : Implements INotifyPropertyChanged
    Private Property m_ItemQty As Integer
    Public Property ItemQty As Integer
        Get
            Return m_ItemQty
        End Get
        Set(value As Integer)
            m_ItemQty = value
            FirePropertyChanged()
        End Set
    End Property
    Public Sub FirePropertyChanged(<CallerMemberName> Optional propName As String = "")
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
    End Sub
    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemUnitPrice As Double

End Class

此致