【发布时间】:2012-02-03 09:31:42
【问题描述】:
我找不到在我的 ComboBox.Items 计数更改时触发的正确事件。有什么办法吗?
【问题讨论】:
标签: wpf events combobox count items
我找不到在我的 ComboBox.Items 计数更改时触发的正确事件。有什么办法吗?
【问题讨论】:
标签: wpf events combobox count items
将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,它们将出现在组合框中
希望对你有帮助
【讨论】:
不要认为当 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)
{
}
【讨论】: