[英]how to bind a ComboBox to a list of string
how to bind a ComboBox to a list of string here is my list : 如何将ComboBox绑定到字符串列表,这是我的列表:
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 请注意,我的comboBox位于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 ) 您不应该在ItemsSource中使用绑定,因为您没有在后面的代码中设置datacontext(在m_Category填充之后)
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. 首先检查是否将DataContext设置为ComboBox,否则绑定将无法工作。
Your XAML file should look something like this: 您的XAML文件应如下所示:
<ComboBox Name="cbPropName" ItemsSource="{Binding Path=m_Category}" />
it should work, if you still have a problem take a look in this post 它应该可以工作,如果仍然有问题,请看这篇文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.