WPF 避免添加重复行 [英] WPF avoid adding a duplicate row
问题描述
我正在使用 vb.net 框架 4.5 和 WPF 项目.
I'm using vb.net framework 4.5 and WPF project.
我有一个按钮,该功能将某个产品信息添加到数据网格中.在我的 vb 代码文件中,我设置了一个产品类
I have a button, the function adds a certain product info to a datagrid. In my vb code file I set a product class
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
目前,如果我多次点击此按钮,数据网格将为同一产品添加多个重复行.我的目标是当多个相同的产品添加到数据网格时,只显示一行,并且同一按钮上的每个额外点击/点击操作只会增加 ItemQty 数量.
Currently, if I tap multiple times of this button, the data grid will add multiple duplicated rows for same product. My goal is when multiple same product add to datagrid, only one row shows and each additional tap/click action on the same button will only increase the ItemQty number.
我该怎么做?谢谢!
推荐答案
首先要防止插入两次:
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 类必须在数量改变时引发一个事件,否则没有可见的变化:
Second the MyProduct class must raise an event when the quantity is changed, otherwise there is no visible change :
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
问候
这篇关于WPF 避免添加重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!