Frank Dzaebel, erstellt am: 17.7.2008, zuletzt geändert:
17.7.2008
Kategorie: WPF, .NET-Version: 3.5, [Download]
Dieser Artikel zeigt eine Möglichkeit in WPF, wie eine ObservableCollection<T>
über eine Änderung eines seiner Elemente nach aussen hin benachrichtigen kann.
Window1.cs:
using System.Windows;
using System.Collections.Specialized;
using System.Diagnostics;
namespace WpfListView
{
/// <summary> Interaktionslogik für Window1.xaml </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Liste liste = (Liste)FindResource("liste");
for (int i = 0; i < 100; i++)
liste.Add(new Customer());
liste.CollectionChanged += new NotifyCollectionChangedEventHandler(liste_CollectionChanged);
liste[3].Nachname = "neu";
}
void liste_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debugger.Break();
}
}
}
Window1.xaml:
<Window x:Class="WpfListView.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfListView">
<Window.Resources>
<local:Liste x:Key="liste" x:Name="liste" />
</Window.Resources>
<ListView ItemsSource="{Binding Source={StaticResource ResourceKey=liste}}">
<ListView.View>
<GridView>
<GridViewColumn Header="Vorname" DisplayMemberBinding="{Binding Path=Vorname}" />
<GridViewColumn Header="Nachname" DisplayMemberBinding="{Binding Path=Nachname}" />
</GridView>
</ListView.View>
</ListView>
</Window>
Liste.cs:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Collections.Specialized;
namespace WpfListView
{
public class Liste : ObservableCollection<Customer>
{
protected override void InsertItem(int index, Customer item)
{
base.InsertItem(index, item);
this[index].PropertyChanged += new PropertyChangedEventHandler(Liste_PropertyChanged);
}
void Liste_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Reset));
}
}
public class Customer : INotifyPropertyChanged
{
#region INotifyPropertyChanged Member
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Vorname
string vorname = "Peter";
public string Vorname
{
get { return vorname;}
set
{
if (value != vorname)
{
vorname = value;
NotifyPropertyChanged("Vorname");
}
}
}
#endregion
#region Nachname
string nachname = "Forstmeier";
public string Nachname
{
get {return nachname;}
set
{
if (value != nachname)
{
nachname = value;
NotifyPropertyChanged("Nachname");
}
}
}
#endregion
}
}