如何在WPF TreeView中修改类以使用其集合
我正试图修改我的对象,使其成为分层收集模型。我需要帮助。我的物品是好的和好的分类:如何在WPF TreeView中修改类以使用其集合,wpf,treeview,class-design,Wpf,Treeview,Class Design,我正试图修改我的对象,使其成为分层收集模型。我需要帮助。我的物品是好的和好的分类: public class Good { int _ID; int _GoodCategory; string _GoodtName; public int ID { get { return _ID; } }
public class Good
{
int _ID;
int _GoodCategory;
string _GoodtName;
public int ID
{
get { return _ID; }
}
public int GoodCategory
{
get { return _GoodCategory; }
set
{
_GoodCategory = value;
}
}
public string GoodName
{
get { return _GoodName; }
set
{
_GoodName = value;
}
}
public Good(IDataRecord record)
{
_ID = (int)record["ID"];
_GoodtCategory = (int)record["GoodCategory"];
}
}
public class GoodCategory
{
int _ID;
string _CategoryName;
public int ID
{
get { return _ID; }
}
public string CategoryName
{
get { return _CategoryName; }
set
{
_CategoryName = value;
}
}
public GoodCategory(IDataRecord record)
{
_ID = (int)record["ID"];
_CategoryName = (string)record["CategoryName"];
}
}
我有两个这样的对象集合:
public class GoodsList : ObservableCollection<Good>
{
public GoodsList()
{
string goodQuery = @"SELECT `ID`, `ProductCategory`, `ProductName`, `ProductFullName` FROM `products`;";
using (MySqlConnection conn = ConnectToDatabase.OpenDatabase())
{
if (conn != null)
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = productQuery;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Add(new Good(rdr));
}
}
}
}
}
public class GoodCategoryList : ObservableCollection<GoodCategory>
{
public GoodCategoryList ()
{
string goodQuery = @"SELECT `ID`, `CategoryName` FROM `product_categoryes`;";
using (MySqlConnection conn = ConnectToDatabase.OpenDatabase())
{
if (conn != null)
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = productQuery;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Add(new GoodCategory(rdr));
}
}
}
}
}
所以我有两个集合,它们从数据库中获取数据。但是我想用HierarchycalDataTemplate使用WPF树视图中的集合。我看到很多帖子都有等级物品的例子,但我不知道如何使我的物品等级化。请提供帮助。将集合属性添加到父类我猜是GoodCategory。您可以将其设置为IList或ObservableCollection。或者,如果您不希望消费代码能够将商品添加到GoodCategory,请使用只读集合。例如:
class GoodCategory
{
private ObservableCollection<Good> _goods = new ObservableCollection<Good>();
public ObservableCollection<Good> Goods
{
get { return _goods; }
}
}
您需要确保此集合与Good.GoodCategory属性正确同步-例如,当Good.GoodCategory属性更改时,商品可能会从其现有的GoodCategory.Goods集合中删除自己,并将自己添加到新的GoodCategory的商品集合中。如果您使用对象关系映射器而不是手工制作的类和SQL语句,那么ORM应该为您解决这个问题