WPF ComboBox binding ItemsSource

前端 未结 3 1618
有刺的猬
有刺的猬 2020-12-16 04:17

I\'m a beginner on WPF and trying to bind the Items of a ComboBox to an ObservableCollection

I used this code:

XAML



        
3条回答
  •  清酒与你
    2020-12-16 05:08

    There are a few things wrong with your current implementation. As others have stated, your list is currently NULL, and the DataContext of the Window is not set.

    Though, I would recommend (especially since you just started using WPF) is learning to do the binding the more 'correct' way, using MVVM.

    See the simplified example below:

    First, you want to set the DataContext of your Window. This will allow the XAML to 'see' the properties within your ViewModel.

    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel();
        }
    }
    

    Next, simply set up a ViewModel class that will contain all of the Window's binding elements, such as:

    public class ViewModel
    {
        public ObservableCollection CmbContent { get; private set; }
    
        public ViewModel()
        {
            CmbContent = new ObservableCollection
            {
                "test 1", 
                "test 2"
            };
        }
    }
    

    Lastly, update your XAML so that the binding path matches the collection:

    
        
    
    

提交回复
热议问题