ItemsSource vs DataContext in binding case

前端 未结 2 2151
感动是毒
感动是毒 2021-02-14 01:47

My main question is about binding case in the scene that we have multiple sources for a control(a combobox inside a datagrid)(or having both datacontext and itemssource). Then h

2条回答
  •  轮回少年
    2021-02-14 02:19

    Its really simple.

    DataContext refers to the same property of the items. It does not get extended and its not dynamic. DataContext applies to children's properties which are currently inside the parent.

    But ItemsSource is dynamic. It gets extended along with the source. Here is a gud example.

    This is a sample xaml.

     
    
    
                   
            
                
                    
                    
                
            
        
        
            
                
                
            
            
        
    
    

    Here is the code behind.

     namespace SilverlightApplication
     {
      public partial class MainPage : UserControl
     {
        public MainPage()
        {
            InitializeComponent();
            loadLists();
        }
    
        private void loadLists()
        {
            ObservableCollection tColl = new ObservableCollection();            
    
            Temp1 t1 = new Temp1();
            t1.Text1 = "DataContext1";
            t1.Text2 = "DataContext2";            
    
            tColl.Add(new Temp2() { Image = "", Data = "Item1" });
            tColl.Add(new Temp2() { Image = "", Data = "Item2" });
    
    
            DataContextStack.DataContext = t1;
            lst2.ItemsSource = tColl;            
        }
    }
    
    public class Temp1
    {
        public string Text1 { get; set; }
        public string Text2 { get; set; }
    
    
    
    }
    
    public class Temp2
    {
        public string Image { get; set; }
        public string Data { get; set; }
    }
    }
    

    As you can see, the DataContext applies to the Textblocks which exist in the StackPanel and refer to one single property that is Text.

    Whereas ItemsSource refers to Source of the Image and Text property of the Textblock and the items inside the list can be extended along with the ObservableCollection.

    Or to make it even simpler to you.

    DataContext - Value is set based on the design. ItemsSource - Value is set based on the logic.

    Hope this helps.

    Mark this as answer, if this answered your question.

提交回复
热议问题