Binding und CrossThreading

 

 

MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CrossThreadCollection
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Kunde> Kunden { get; set; }
private object _listLock = new object();

public MainWindow()
{
Kunden = new ObservableCollection<Kunde>();
BindingOperations.EnableCollectionSynchronization(Kunden, _listLock);

InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
Kunde kunde1 = new Kunde { Name = "Star Wars AG" };
Kunde kunde2 = new Kunde { Name = "Rebellen GmbH" };
Kunde kunde3 = new Kunde { Name = "Klon Krieger GbR" };

lock (_listLock)
{
Kunden.Clear();

Kunden.Add(kunde1);
Kunden.Add(kunde2);
Kunden.Add(kunde3);
}
});

}
}
}

 

MainWindow.xaml:
<Window x:Class="CrossThreadCollection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CrossThreadCollection"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" x:Name="window">
<Grid>
<StackPanel>
<ListBox ItemsSource="{Binding ElementName=window, Path=Kunden}" DisplayMemberPath="Name" Width="250" Height="150" />
<Button Width="250" Content="Kundendaten laden..." Click="Button_Click" />
</StackPanel>
</Grid>
</Window>


Kunde.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossThreadCollection
{
public class Kunde
{
public string Name { get; set; }
}
}

Top