我正在尝试将代码中的 ComboBox 添加到 WPF UserControl。ComboBox 按预期添加并显示我在 ComboBox 中设置的默认值,但是当我按下它时,它并没有打开。
这是试图绑定数据的代码,只是其中的一部分:
public class SelectRecentData : INotifyPropertyChanged
{
public ObservableCollection<ComboBoxItem> projectItems { get; set; }
private ComboBoxItem _selectedprojectItem;
public ComboBoxItem SelectedprojectItem
{
get
{
return _selectedprojectItem;
}
set
{
this._selectedprojectItem = value;
this.onPropertyChanged("SelectedprojectItem");
}
}
}
这是生成和插入 ComboBox 的代码:
SelectRecentData Data = new SelectRecentData();
ComboBox cbo = new ComboBox();
cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding(){
bind.Source = Data; //Data is the class mentioned above
bind.Path = new PropertyPath("projectItems");}
cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding(){
bind.Source = Data;
bind.Path = new PropertyPath("SelectedprojectItem");});
cbo.Name = name;
cbo.Margin = new Thickness(0.5,0.5,0.5,0.5);
cbo.Width = 200;
sp.Children.Add(cbo); //sp is the StackPanel
如果您按下页面上的按钮,这是测试添加项目的代码:
var defaultvalue = new ComboBoxItem { Content = "Added "+mycounter };
Data.projectItems.Add(defaultvalue);
Data.SelectedprojectItem = defaultvalue;
mycounter++;