Binding ObservableCollection to WPF ListBox

前端 未结 3 957
野的像风
野的像风 2020-12-15 21:19

I have the below code-behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            


        
3条回答
  •  天涯浪人
    2020-12-15 22:21

    Yes, you'll need to set the DataContext somehow. It doesn't have a DataContext, because the Window doesn't have a DataContext unless it is set. The ListBox will get the DataContext if you do this in the constructor.

    public MainWindow() 
    { 
        InitializeComponent(); 
        this.DataContext = this;
    } 
    

    Otherwise you can use RelativeSource, ElementName etc. in the Binding but I guess you knew that =)

提交回复
热议问题