使用WPF在XAML中实现CollectionChanged处理程序

时间:2013-01-18 00:01:58

标签: c# wpf events user-interface event-handling

我使用位于stackoverflow:event-fired-when-item-is-added-to-listview的解决方案来利用CodeBehind中的接口INotifyCollectionChanged。有没有办法在XAML中添加这个EventHandler?

基本上,我希望用XML定义这一行:

((INotifyCollectionChanged)lbFiles.Items).CollectionChanged += lbFiles_SelectionChanged; 

1 个答案:

答案 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
    }
}