2016-01-15 108 views
0

在一個較早的WinForms應用程序中,這工作,但在WPF中它只會移動該項目一次,唯一當前的解決方法是將其保存到後端數據庫,再次打開並移動一個空間。列表項由一個DataTableWPF列表框 - 上下移動項目

Private Sub Reports_BalanceSheet_ListBoxMoveUp(LB As ListBox, DT As DataTable, DisplayName As String, Optional MasterListBox As ListBox = Nothing) 
    Try 
     Dim StartIndex As Integer = LB.SelectedIndex 
     Dim CatID As Integer = 0 

     'Update the datasource 
     Dim SR() As DataRow 
     If DisplayName = "Name" Then 
      SR = DT.Select("ID > 0 AND FormID = " & Form_ID, Nothing) 
     Else 
      CatID = MasterListBox.SelectedValue 
      'Check that the positions are correct 
      If DataChanged = False Then 
       Dim vRowID As Integer = 0 
       For Each Row As DataRow In DT.Rows 
        If Row("FormID") = Form_ID And Row("CatID") = CatID Then 
         Row("Position") = vRowID 
         vRowID += 1 
        End If 
       Next 
      End If 

      SR = DT.Select("ID > 0 AND FormID = " & Form_ID & " AND CatID = " & CatID, "Position") 
     End If 
     Dim vString As String = "" 
     Dim vUpperID As Integer = 0 
     Dim vCurrentID As Integer = 0 
     For Each Row As DataRow In SR 
      Dim vPos As Integer = Row("Position") 
      If vPos = StartIndex - 1 Then 
       vUpperID = Row("ID") 
      End If 
      If vPos = StartIndex Then 
       vCurrentID = Row("ID") 
      End If 
     Next 
     If Not vUpperID = 0 And Not vCurrentID = 0 Then 
      DT.Select("ID = " & vUpperID)(0)("Position") = StartIndex 
      DT.Select("ID = " & vCurrentID)(0)("Position") = StartIndex - 1 
      If DisplayName = "Name" Then 
       DT.DefaultView.RowFilter = "FormID = " & Form_ID 
      Else 
       DT.DefaultView.RowFilter = "FormID = " & Form_ID & " AND CatID = " & CatID 
      End If 

      DT.DefaultView.Sort = "Position" 
      DT = DT.DefaultView.ToTable 
      DT.AcceptChanges() 

      With LB 
       .SelectedValuePath = "ID" 
       .DisplayMemberPath = DisplayName 
       .ItemsSource = DT.DefaultView 
       .SelectedValue = vCurrentID 
       .UpdateLayout() 
      End With 
     End If 


    Catch ex As Exception 
     EmailError(ex) 
    End Try 
End Sub 

回答

0

提供明白了:-)

Dim StartIndex As Integer = LB.SelectedIndex 
     Dim vTotalRows As Integer = DT.Rows.Count - 1 
     If Not StartIndex = vTotalRows Then 
      Dim vSelected As DataRow = DT.Rows(StartIndex) 
      Dim vNew As DataRow = DT.NewRow() 
      vNew.ItemArray = vSelected.ItemArray 
      DT.Rows.Remove(vSelected) 
      DT.Rows.InsertAt(vNew, StartIndex + 1) 

      LB.SelectedIndex = StartIndex + 1 

      Dim vPos As Integer = 0 
      For Each Row As DataRow In DT.Rows 
       Row("Position") = vPos 
       vPos += 1 
      Next 
     End If 
這種方式工作(和更少的代碼)