您应该只是在CollectionChanged
绑定到您的 ListBox/ListView 等的集合上创建事件,从后面的代码中直接访问控件不是 WPF 做事的方式。
例子:
xml:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="340" Width="480" Name="UI" >
<Grid DataContext="{Binding ElementName=UI}">
<ListBox ItemsSource="{Binding MyProperty}" />
</Grid>
</Window>
代码:
public partial class MainWindow : Window
{
private ObservableCollection<string> _myProperty = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
MyProperty.CollectionChanged += MyProperty_CollectionChanged;
}
public ObservableCollection<string> MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
void MyProperty_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Collection Changed
}
}