Implementing CollectionChanged Handler in XAML with WPF

限于喜欢 提交于 2019-12-24 14:34:10

问题


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?

Essentially, I want this line defined in XML:

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

回答1:


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.

Example:

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>

Code:

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


来源:https://stackoverflow.com/questions/14390368/implementing-collectionchanged-handler-in-xaml-with-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!