-1

我在 Form1 的 VB.Net 应用程序中有 2 个表单 我有一个 Listview 元素 我想在 Form2 中显示相同的 Listview 但大小不同 最好的方法是什么?谢谢

4

1 回答 1

0

不,没有将一个控件的内容复制到另一个控件的内置方法ListView。相反,您应该重组代码,以便业务逻辑与 UI 分离。从 API 获取数据的逻辑和ListView用该数据填充控件的逻辑都应该在一个单独的公共类中,任何形式都可以使用。为此,您需要将数据以某种数据结构存储在内存中,以便在表单、类和方法之间轻松传递。例如,如果列表中的每个项目都可以表示为一个Atom类,我建议使用一个List(Of Atom)对象来保存数据。例如,您的公共类可能是这样的:

Public Class ShoppingBusiness
    Public Function GetData() As List(Of Atom)
        ' Get data from API and return it as a List(Of Atom) object
    End Function        

    Public Sub LoadList(atoms As List(Of Atom), list As ListView)
        ' Load the ListView control with the data
    End Sub
End Class

一旦业务逻辑被分解成它自己的类,您就可以轻松地从任何形式访问所有逻辑,而无需复制所有代码。但是,在本例中,调用不是两种形式,ShoppingBusiness.GetData因为这可能是一个缓慢的方法,您只需要执行一次,然后使用相同的数据来填充两个ListView控件。例如,如果Form1显示Form2,它可以这样做:

Public Class Form1
    Private _data As List(Of Atom)
    Private _business As ShoppingBusiness = New ShoppingBusiness()

    Private Sub refreshList()
        _data = _business.GetData()
        _business.LoadList(_data, ListView1)
    End Sub

    Private Sub showForm2()
        Dim form2 As Form2 = New Form2()
        form2.Data = _data
        form2.Show()
    End Sub
End Class

Public Class Form2
    Private _data As List(Of Atom)
    Private _business As ShoppingBusiness = New ShoppingBusiness()

    Public Property Data() As List(Of Atom)
        Get
            Return _data
        End Get
        Set(ByVal value As List(Of Atom))
            _data = value
        End Set
    End Property

    Private Sub refreshList()
        _business.LoadList(_data, ListView2)
    End Sub
End Class

As you can see in this example, Form1 will keep a copy of the data in memory after it gets it. It keeps the data in it's private _data field. When it creates a new Form2 object, before it shows it, it gives it a reference to the data that it already has in memory. Then, Form2 can use the same LoadList method to load the data into the list, but it doesn't have to get the data from the API again because the data was given to it by Form1.

于 2012-07-02T02:27:54.060 回答