i'am trying to modify my objects to make hierarchical collection model. I need help. My objects are Good and GoodCategory:
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"];
}
}
And I have two Collections of these objects:
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)
开发者_StackOverflow社区 {
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = productQuery;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Add(new GoodCategory(rdr));
}
}
}
}
}
So I have two collections which takes data from the database. But I want to use thats collections in the WPF TreeView with HierarchicalDataTemplate. I saw many post's with examples of Hierarlichal Objects, but I steel don't know how to make my objects hierarchicaly. Please help.
Add a collection property to the "parent" class (I guess GoodCategory). You might make this an IList<ChildType>
or an ObservableCollection<ChildType>
. (Or, if you don't want consuming code to be able to add Goods to a GoodCategory, use a read-only collection.) For example:
class GoodCategory
{
private ObservableCollection<Good> _goods = new ObservableCollection<Good>();
public ObservableCollection<Good> Goods
{
get { return _goods; }
}
}
You will need to ensure that this collection is properly synchronised with the Good.GoodCategory property -- for example, when the Good.GoodCategory property changes a Good might remove itself from its existing GoodCategory.Goods collection and add itself to the new GoodCategory's Goods collection. If you use an object-relational mapper rather than handcrafted classes and SQL statements than the ORM should take care of this for you.
精彩评论