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));
}
}
}
}
}
所以我有两个从数据库中获取数据的集合。但我想在WPF TreeView中使用那些集合与HierarchicalDataTemplate。我看到很多帖子都有Hierarlichal Objects的例子,但是我不知道如何使我的对象具有层次性。请帮忙。
答案 0 :(得分:0)
将一个集合属性添加到“父”类(我想是GoodCategory)。您可以将其设为IList<ChildType>
或ObservableCollection<ChildType>
。 (或者,如果您不希望使用代码将商品添加到GoodCategory,请使用只读集合。)例如:
class GoodCategory
{
private ObservableCollection<Good> _goods = new ObservableCollection<Good>();
public ObservableCollection<Good> Goods
{
get { return _goods; }
}
}
您需要确保此集合与Good.GoodCategory属性正确同步 - 例如,当Good.GoodCategory属性更改时,Good可能会将其自身从其现有的GoodCategory.Goods集合中移除并将其自身添加到新集合中GoodCategory的商品系列。如果你使用对象关系映射器而不是手工制作的类和SQL语句,那么ORM应该为你处理这个问题。