C# 如何在wpf中动态添加ComboBox项
我是WPF的新手 我正在动态地将项目添加到组合框中,如下所示C# 如何在wpf中动态添加ComboBox项,c#,wpf,C#,Wpf,我是WPF的新手 我正在动态地将项目添加到组合框中,如下所示 objComboBox.Items.Add("<--Select-->"); objComboBox.Items.Add(“”); 现在我需要为特定项设置值和索引。在asp.net中,我正在做 DropDownList1.Items.FindByText("<--Select-->").Value ="-1" DropDownList1.Items.FindByText(“”).Value=“-1
objComboBox.Items.Add("<--Select-->");
objComboBox.Items.Add(“”);
现在我需要为特定项设置值和索引。在asp.net中,我正在做
DropDownList1.Items.FindByText("<--Select-->").Value ="-1"
DropDownList1.Items.FindByText(“”).Value=“-1”
我在wpf中找不到合适的方法。我如何才能做到这一点?始终尝试避免直接访问UI。使用
绑定
将数据绑定到控件,并添加
,搜索
,删除
任何内容仅在数据上。更改UI将处理WPF绑定本身
例如:XAML:
<ComboBox ItemsSource="{Binding cbItems}" SelectedItem="{Binding SelectedcbItem}"/>
代码隐藏:
public ObservableCollection<ComboBoxItem> cbItems { get; set; }
public ComboBoxItem SelectedcbItem { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
cbItems = new ObservableCollection<ComboBoxItem>();
var cbItem = new ComboBoxItem { Content = "<--Select-->" };
SelectedcbItem = cbItem;
cbItems.Add(cbItem);
cbItems.Add(new ComboBoxItem { Content = "Option 1" });
cbItems.Add(new ComboBoxItem { Content = "Option 2"});
}
publicobservableCollection cbItems{get;set;}
公共ComboBoxItem SelectedcbItem{get;set;}
公共主窗口()
{
初始化组件();
DataContext=this;
cbItems=新的ObservableCollection();
var cbItem=新ComboBoxItem{Content=”“};
SelectedcbItem=cbItem;
cbItems.Add(cbItem);
添加(新ComboBoxItem{Content=“Option 1”});
添加(新ComboBoxItem{Content=“Option 2”});
}
combo.SelectedIndex=combo.Items.IndexOf(“”);
但更好的方法是使用snurre提到的绑定,如果它是列表中的第一个,您应该使用: objComboBox.SelectedIndex=0; 或 DropDownList1.SelectedIndex=0 如果不是第一个,则使用: objComboBox.SelectedItem=“”; 或
DropDownList1.SelectedItem=“” 我很好奇。cbItem在添加到cbItems之前先添加到SelectedcbItem。当绑定机制看到SelectedcdItem更改为尚未在绑定集合中的对象时,是否存在任何问题或副作用?
combo.SelectedIndex = combo.Items.IndexOf("<--Select-->");