Can't get WPF ListView to bind to ObservableCollection

前端 未结 1 522
心在旅途
心在旅途 2021-01-18 04:43

I\'ve been playing around with WPF for the first time, specifically using a ListView that I want to bind to a ObservableCollection that is a property on the code-behind page

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 05:17

    Uh, you're trying to do something simple with some terrible magic ;) Your binding should look like {Binding Path=Code}. To make this work you should also set DataContext to this, just like you wrote. This should give you simplest binding. Magic with finding ancestors is not necessary in here.

    In advanced applications you should rather use Model - View - ViewModel pattern and set data context to ViewModel object rather than to this, but just for testing and trying WPF out, this approach should be ok.

    Here is some sample:

    
    
        
    
    

    And code behind:

    using System.Collections.ObjectModel;
    using System.Windows;
    
    namespace binding_test
    {
        public partial class MainWindow : Window
        {
            public ObservableCollection Code { get; set; }
            public MainWindow()
            {
                InitializeComponent();
                Code = new ObservableCollection();
                Code.Add(1);
                this.DataContext = this;
            }
        }
    }
    

    And here is how you should create listview for your sample. You have special class and you probably don't want to display ToString() result on each object. To display element any way you could imagine, you should use data template and there create controls and bind them to properties of element, that was in list you've bind ListView.

        
            
                
                    
                
            
        
    

    0 讨论(0)
提交回复
热议问题