ComboBox.Items计数更改时触发事件? [英] Event firing when ComboBox.Items count changed?

查看:134
本文介绍了ComboBox.Items计数更改时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到当ComboBox.Items计数更改时触发的适当事件.有什么办法吗?

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

推荐答案

将ComboBox ItemsSource绑定到ObservableCollection,然后您可以捕获ObservableCollection的事件CollectionChanged

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

在wpf中,建议使用绑定而不是直接访问UI元素属性,当然最好使用MVVM,但也可以不用它而生活

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

在Windows或UserControls C#代码中,您可以保留这样的属性

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

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

在构造函数中初始化

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

不是像这样在xaml中命名您的UserControl

than name your UserControl in xaml like this

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

这样编写您的ComboBox

write your ComboBox like this

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

现在,无需向组合框元素中添加和删除项目,而是将tham添加到MyCollection中,它们将出现在组合框中

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

希望这会有所帮助

这篇关于ComboBox.Items计数更改时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆