Why are DataContext and ItemsSource not redundant?

后端 未结 2 1510
灰色年华
灰色年华 2020-12-13 04:15

In WPF Databinding, I understand that you have DataContext which tells an element what data it is going to bind to and ItemsSourc

2条回答
  •  无人及你
    2020-12-13 04:33

    ItemsSource property will be binded with collection object directly OR collection property of binding object of DataContext property.

    Exp:

    Class Root
    {
       public string Name;
       public List childRoots = new List();
    }
    
    Class ChildRoot
    {
       public string childName;
    }
    

    There will be two ways to bind ListBox control:

    1) Binding with DataContext:

        Root r = new Root()
        r.Name = "ROOT1";
    
        ChildRoot c1 = new ChildRoot()
        c1.childName = "Child1";
        r.childRoots.Add(c1);
    
        c1 = new ChildRoot()
        c1.childName = "Child2";
        r.childRoots.Add(c1);
    
        c1 = new ChildRoot()
        c1.childName = "Child3";
        r.childRoots.Add(c1);
    
    treeView.DataContext = r;
    
    
    
    

    2) Binding with ItemSource:

    ItemsSource property takes collection always. here we have to bind collection of Root

    List lstRoots = new List();
    lstRoots.Add(r);
    
    
    

    In First example we have bind DataContext which has object inside that object we have collection which we binded with ItemSource property where in Second example we have directly bind ItemSource property with collection object.

提交回复
热议问题