使用WPF在XAML中实现CollectionChanged处理程序 [英] Implementing CollectionChanged Handler in XAML with WPF
问题描述
我使用的解决方案位于 stackoverflow:event-fired-when -item-is-add-to-listview 以使用CodeBehind中的INotifyCollectionChanged接口.有没有办法在XAML中添加此EventHandler?
I used the solution located at stackoverflow:event-fired-when-item-is-added-to-listview to utilize interface INotifyCollectionChanged in CodeBehind. Is there a way to add this EventHandler within the XAML?
本质上,我希望此行以XML定义:
Essentially, I want this line defined in XML:
((INotifyCollectionChanged)lbFiles.Items).CollectionChanged += lbFiles_SelectionChanged;
推荐答案
您应该只在绑定到ListBox/ListView等的集合上创建CollectionChanged
事件,从后面的代码严格访问控件不是WPF做事的方式.
You should just be creating the CollectionChanged
event on the collection that is bound to your ListBox/ListView etc, accessing controls derictly from code behind is not the WPF way to do things.
示例:
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
}
}
这篇关于使用WPF在XAML中实现CollectionChanged处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!