正确使用ListView和ObservableCollection的方法

本文关键字:ObservableCollection 方法 ListView | 更新日期: 2023-09-27 17:49:39

我使用ListView与项目绑定为ObservableCollection。每个对象都有自己的get、set,例如:

public string NamePar
        {
            get
            {
                if (_namePar == null)
                {
                    if (_productID > 0)
                    {
                        using (SqlConnection conn = new SqlConnection(cString.c_String))
                        {
                            conn.Open();
                            using (SqlCommand cmd = new SqlCommand("...", conn))
                            {
                                using (SqlDataReader rdr = cmd.ExecuteReader())
                                {
                                    while (rdr.Read())
                                    {
                                        _namePar = rdr[0].ToString();
                                    }
                                }
                            }
                        }
                    }
                }
                return _namePar;
            }
            set
            {
                if (_namePar == value)
                    return;
                _namePar = value;
                NotifyPropertyChanged("NamePar");
            }
        }

所以我有一个问题:

  • 在每个get中使用SqlConnection是否正确?
  • 我应该使用一个SqlConnection并使用它而不打开新的每一次?
  • 为什么当我在ListView中选择项目时,它每次都去get(有时甚至是20倍的相同的得到?),例如它是productCount,然后到productPrice,然后再到count等等?我知道如果value != null那么它将返回previous (private)值,但也许我做错了什么

非常感谢您的帮助!:)

正确使用ListView和ObservableCollection的方法

别别别别别!

不要在getter中打开SQLConnections !

一个更好的方法是只在需要时设置NamePar属性。

下面是我的意思的一个例子:

为项目创建一个类,如下所示:

public class MyItem
{
    public string Name { get; set; }
    ...
}

创建项目列表以填充其属性值的人有责任。所以你需要创建一个方法来刷新列表。例如:

public void Refresh()
{
    //Open a SQL Connection
    //Get the records you need
    //Populate an observable collection of [MyItem] with the records from the database.
}

通过将SQL连接的东西移动到食物链的更高位置,到视图模型,您已经获得了一些性能,因为您不再在属性getter中运行查询。