Event firing when ComboBox.Items count changed?

2019-08-04 12:09发布

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

2条回答
冷血范
2楼-- · 2019-08-04 12:30

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

查看更多
Anthone
3楼-- · 2019-08-04 12:35

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)
{

}
查看更多
登录 后发表回答