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"/>
Plz note that my comboBox is inside a DataTemplate Thks
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 ;
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.