我使用了位于stackoverflow:event-fire - when-item-isadd-listview的解决方案来利用CodeBehind中的INotifyCollectionChanged接口。有没有办法在XAML中添加这个eventandler ?
我想用XML定义这一行:
((INotifyCollectionChanged)lbFiles.Items).CollectionChanged += lbFiles_SelectionChanged;
你应该只是在集合上创建CollectionChanged
事件,绑定到你的ListBox/ListView等,直接从后面的代码访问控件不是WPF做事情的方式。
的例子:Xaml:
<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
}
}