[英]how to bind a ComboBox to a list of string
如何將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"/>
請注意,我的comboBox位於DataTemplate Thks內部
您不應該在ItemsSource中使用綁定,因為您沒有在后面的代碼中設置datacontext(在m_Category填充之后)
MyComboBox.ItemsSource = m_Category ;
否則,您應該創建一個包含此類屬性的類,並且綁定將起作用
public class MyDataContext
{
ObservableCollection<string> m_Category =
new ObservableCollection<string>();
public ObservableCollection<string> M_Category
{ get;set}
}
//像這樣更改綁定
<ComboBox x:Name="MyComboBox" Height="Auto" Width="Auto"
ItemsSource="{Binding M_Category, NotifyOnTargetUpdated=True,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" SelectedIndex ="0"
SelectionChanged ="MyComboBox_SelectionChanged"/>
在主窗口中,您可以執行以下操作
public MainWindow()
{
InitializeComponent();
MyDataContext myDataContext = new MyDataContext();
//for example here
For(i=0;i<100;i++)
myDataContext.M_category.Add(yourItem)
this.DataContext = myDataContext ;
}
首先檢查是否將DataContext設置為ComboBox,否則綁定將無法工作。
您的XAML文件應如下所示:
<ComboBox Name="cbPropName" ItemsSource="{Binding Path=m_Category}" />
它應該可以工作,如果仍然有問題,請看這篇文章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.