WPF ComboBox binding ItemsSource

前端 未结 3 1616
有刺的猬
有刺的猬 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 04:44

       public MainWindow()
        {
    
            InitializeComponent();
            cmbContent=new ObservableCollection();
            cmbContent.Add("test 1");
            cmbContent.Add("test 2");
            cmbTest.ItemsSource = cmbContent;
    
        }
        public ObservableCollection cmbContent { get; set; }
    

    The code above don't use any binding, that's mean using it there no need to bind the Combobox's ItemSource, if you wan't to use binding you need to

    First: Set the DataContext from the CodeBehind (ViewModel) using :

    this.DataContext=this;
    

    or from the Xaml:

    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    

    Second : use the Binding in the ItemSource Just like you did ItemsSource="{Binding Path=cmbContent}" you may also considere using INotifyPropertyChanged Interface if you want to Notify the UI in case of any changes in a property

提交回复
热议问题