将数据绑定到treeView c#

时间:2015-07-07 12:18:36

标签: c# wpf treeview

我希望我的程序像这样工作: 1.它从MS SQL获取数据 2.根据此数据创建树(数据行) 我有几个textBoxex,我想用基于点击节点的数据填充它们。 我为SQL连接创建了类:

setNextNode(...)

和treeView创建者:

 class Baza
{
    private SqlConnection connection;
    string dbdir = "Data Source=CS24\\SQLEXPRESS;user id=sa;password=alamakota;database=SHARP;connection timeout=3";
    public Baza()
    {
      connection = new SqlConnection();
      connection.ConnectionString = dbdir;
      connection.Open();
    }
    public DataTable get_data(string q) 
    {
        DataTable dt = new DataTable(); 
        SqlDataReader dr ; 
        SqlCommand sqlc = new SqlCommand(q);
        sqlc.Connection = this.connection;
        dr = sqlc.ExecuteReader();
        dt.Load(dr);
        return dt;
    }
}

我认为该节点应该有ID,我可以使用它来填充数据,但我真的不知道该怎么做。你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的麻烦,我这样做了:

(我在ParentID,IsGroup,OrderInGroup列中有分层数据)

  • 为TreeViewItems

    创建一个类
     public class xTreeViewItem : INotifyPropertyChanged
     {
          public int id { get; set; }
          public string Header { get; set; }
          public int parent;
          public List<xTreeViewItem > children { get; set; }
          public bool isGroup = false;
          public bool ParentResolved = false;
          public float order {get;set;}
    
          public void NotifyPropertyChanged(string info)
          {
               if (PropertyChanged != null)
               {
                     PropertyChanged(this, new PropertyChangedEventArgs(info));
               }
          }
          public event PropertyChangedEventHandler PropertyChanged;
     }
    
  • 现在创建一个包含SQL数据的列表

    private void LoadTree()
    {
        ObservableCollection<xTreeViewItem> treeSource = new ObservableCollection<xTreeViewItem>();
        List<xTreeViewItem> Buffer = new List<xTreeViewItem>();
        foreach (DataRow row in table.Rows)
        {
             xTreeViewItem itm = new TreeViewItem();
             // Load the required heirarchial data
             Buffer.Add(itm);
        }
    
        for (int i = Buffer.Count - 1; i >= 0; i--)
        {
            if (Buffer[i].parentID != 0)
            {
                if (Buffer[i].ParentResolved)
                    Buffer.RemoveAt(i);
                else
                {
                    Buffer[i].ParentResolved = true;
    
                    while (Buffer.Any(c => (c.parentID == Buffer[i].menuID && !c.ParentResolved)))
                    {
                        Buffer[i].children.Add(FindChildren(Buffer[i]));
                    }
                    xTreeViewItem parent = Buffer.First(c => c.menuID == Buffer[i].parentID);
                    parent.children.Add(Buffer[i]);
                    Buffer[i].parent = parent;
    
                    Buffer.RemoveAt(i);
                }
            }
        }
        // remaining items acts as mainItems, so add it to the treeSource
        foreach (xTreeViewItem x in Buffer)
        {
             treeSource.Add(x);
        }
        treeView.ItemsSource = treeSource;
    }
    
    xTreeViewItem FindChildren(xMenuItem x)
    {
        List<xTreeViewItem > subBuffer = Buffer.Where(c => (c.parentID == x.menuID && !c.ParentResolved)).ToList(); // if there is, get all of them to a list
    
        subBuffer = subBuffer.OrderBy(c => c.order).ToList();    // << THIS IS CRAZY, BUT FIXES :P // order all of them by their 'order' property
        int indx = Buffer.IndexOf(subBuffer[0]);                                                    // get the first item after ordering
    
        Buffer[indx].ParentResolved = true;
        Buffer[indx].parent = x;                // changing parentresolved property to prevent infinte loops
    
        while (Buffer.Any(c => (c.parentID == Buffer[indx].menuID && !c.ParentResolved))) // again checking if the current child got any other child.
        {
            Buffer[indx].children.Add(FindChildren(Buffer[indx])); // adding all the childs                     
        }
    
        return Buffer[indx]; // return the child
    
    }
    

在XAML中:把它作为TreeView的ItemTemplate:)

    <TreeView.ItemTemplate>
          <HierarchicalDataTemplate ItemsSource="{Binding children}">
                  <ContentPresenter Content="{Binding Header}" Margin="2,0"/>
          </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>

这对我有用:P 要获取所选项目,只需使用:

xTreeViewItem selectedItem = (xTreeViewItem)treeView.SelectedItem;

使用此'selectedItem'更新您的视图; .. :))

希望它有所帮助:)

**有时这些项目可能会反转。只需给出List.Reverse();在它是这样的地方,我没有自己运行代码,无论如何这应该适用于所有类型,例如从数据库加载MenuItems和desplaying(如果你有多种语言很有用):)

**我只有18岁:P还没有获得CS学位,这只是我提出的代码:)是的,可能存在缺陷但它对我有用:P

:)