我使用位于stackoverflow:event-fired-when-item-is-added-to-listview的解决方案来利用CodeBehind中的接口INotifyCollectionChanged。有没有办法在XAML中添加这个EventHandler?
基本上,我希望用XML定义这一行:
((INotifyCollectionChanged)lbFiles.Items).CollectionChanged += lbFiles_SelectionChanged;
答案 0 :(得分:0)
你应该只是在绑定到ListBox / ListView等的集合上创建CollectionChanged
事件,从代码背后访问控件并不是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
}
}