1

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

本质上,我希望在 XML 中定义这一行:

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

1 回答 1

0

您应该只是在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
    }
}
于 2013-01-18T01:34:55.363 回答