MRebai
MRebai

Reputation: 5474

how to bind a ComboBox to a list of string

how to bind a ComboBox to a list of string here is my list :

  public ObservableCollection<string> m_Category = 
                                              new ObservableCollection<string>();

 <ComboBox x:Name="MyComboBox" Height="Auto" Width="Auto"  
        ItemsSource="{Binding m_Category, NotifyOnTargetUpdated=True,Mode=TwoWay,
        UpdateSourceTrigger=PropertyChanged}" SelectedIndex ="0"  
        SelectionChanged ="MyComboBox_SelectionChanged"/>

Edit

Plz note that my comboBox is inside a DataTemplate Thks

Upvotes: 0

Views: 115

Answers (2)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13794

you should not use binding here in your ItemsSource because you don't have a datacontext set here just in code behind do this (after m_Category filling )

MyComboBox.ItemsSource =  m_Category ; 

Otherwise you should create a class contains a property like this and your bind will work

 public class MyDataContext
        {
    ObservableCollection<string> m_Category = 
                                              new ObservableCollection<string>();
        public  ObservableCollection<string>   M_Category 
    { get;set}
      }

//Change your bind like this

 <ComboBox x:Name="MyComboBox" Height="Auto" Width="Auto"  
        ItemsSource="{Binding M_Category, NotifyOnTargetUpdated=True,Mode=TwoWay,
        UpdateSourceTrigger=PropertyChanged}" SelectedIndex ="0"  
        SelectionChanged ="MyComboBox_SelectionChanged"/>

in your main window you can do something like this

 public MainWindow()
    {
        InitializeComponent();
         MyDataContext myDataContext =  new  MyDataContext(); 
           //for example here  
            For(i=0;i<100;i++)
                    myDataContext.M_category.Add(yourItem)
        this.DataContext =  myDataContext ; 
    }

Upvotes: 1

Ofir
Ofir

Reputation: 5319

First of all check if you set a DataContext to your ComboBox otherwise the binding won't work.

Your XAML file should look something like this:

 <ComboBox Name="cbPropName" ItemsSource="{Binding Path=m_Category}" />

it should work, if you still have a problem take a look in this post

Upvotes: 0

Related Questions