我找不到在我的 ComboBox.Items 计数更改时触发的正确事件。有什么办法吗?
问问题
2737 次
2 回答
2
将 ComboBox ItemsSource 绑定到 ObservableCollection,然后就可以捕捉到 ObservableCollection 的 CollectionChanged 事件
编辑:
在 wpf 中建议使用绑定而不是直接访问 UI 元素属性,当然使用 MVVM 更好,但你也可以没有它
在您的 Windows 或 UserControls C# 代码中,您可以保留这样的属性
public ObservableCollection<string> MyCollection{get;set;}
在构造函数中初始化它
MyCollection = new ObservableCollection<string>()
MyCollection.CollectionChanged += SomeMethod;
而不是像这样在 xaml 中命名您的 UserControl
<UserControl Name="myUserControl".../>
像这样写你的组合框
<ComboBox ItemsSource="{Binding ElementName=myUserControl, Path=MyCollection}"...
现在不是向组合框元素添加和删除项目,而是将 tham 添加到 MyCollection,它们将出现在组合框中
希望这可以帮助
于 2012-02-03T09:41:20.303 回答
0
不要认为当 ComboBox.Items 计数发生变化时会触发任何事件。您可能应该在添加或删除项目时执行代码。
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
或者
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
于 2012-02-03T09:43:49.393 回答