How to launch the simplest code illustrating Master-Detail (compound List) object databinding in WPF?

后端 未结 2 2053
面向向阳花
面向向阳花 2020-12-22 05:47

I am trying to run (in C# 4.0, Visual Studio 2010) the code from

  • Unable to display a List as one of the columns of my view with ItemsControl and StackPanel?
2条回答
  •  悲&欢浪女
    2020-12-22 06:44

    First of all myOrders has to be a public property. it cannot be seen even if it's a public variable, secondly to make the view(XAML) aware of what's going in the code behind you need to set DataContext = this; in the window's constructor

    Set a property like this : public List myOrder {get;set;}

    If you need to update the view from code behind then you need to implement INotifyPropertyChanged interface. it's responsible of doing update view job. Here is a small tutorial from MSDN.

    Last thing, (From my experience) you should go with a property of type ObservableCollection instead of List.

    XAML :

    
      
        
          
          
            
              
    
              
                
                  
                  
                    
                      
                        
                        
                      
                      
                      
                    
                  
                
              
            
          
        
      
    
    

    Code behind :

      /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public ObservableCollection MyOrders
        {
            get { return _myOrders; }
            set { _myOrders = value; OnPropertyChanged("MyOrders"); }
        }
    
        Order order1 = new Order
         {
             OrderName = "Order1",
             PartsList = new List()
            {
                new Parts {PartName = "Part11", PartQuantity = 11},
                new Parts {PartName = "Part12", PartQuantity = 12}
            }
         };
    
        private ObservableCollection _myOrders;
    
        public MainWindow()
        {
            InitializeComponent();
            MyOrders = new ObservableCollection();
            MyOrders.Add(order1);
            DataContext = this;
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
        public class Order
        {
            public string OrderName { get; set; }
            public List PartsList { get; set; }
        }
    
        public class Parts
        {
            public string PartName { get; set; }
            public double PartQuantity { get; set; }
            }
    }
    

提交回复
热议问题