问题
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