Event firing when ComboBox.Items count changed?

孤街浪徒 提交于 2019-12-13 17:27:26

问题


I couldn't find a proper event which fires when my ComboBox.Items count changed. Is there any way to do so?


回答1:


Bind ComboBox ItemsSource to ObservableCollection, then you can catch the event CollectionChanged of ObservableCollection

EDIT:

In wpf it is recommended to use binding instead of accessing UI element properties directly, of course better to use MVVM, but you can live without it too

in your Windows or UserControls C# code you can keep property like this

public ObservableCollection<string> MyCollection{get;set;}

Initialize it in constructor

MyCollection = new ObservableCollection<string>()
MyCollection.CollectionChanged += SomeMethod;

than name your UserControl in xaml like this

<UserControl Name="myUserControl".../>

write your ComboBox like this

<ComboBox ItemsSource="{Binding ElementName=myUserControl, Path=MyCollection}"...

now instead of adding and removing items to combobox element, add tham to MyCollection, they will appear in combobox

Hope this helps




回答2:


Don't think that there is any event to fire when ComboBox.Items count changed. You probably should do the code when you add or remove the items.

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

End Sub

OR

protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}


来源:https://stackoverflow.com/questions/9126424/event-firing-when-combobox-items-count-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!