Model:
public class User : INotifyPropertyChanged
{
public override string ToString()
{
return Username;
}
private Int32 _ID;
public Int32 ID
{
get { return _ID; }
set
{
if (value != _ID)
{
_ID = value;
OnPropertyChanged();
OnPropertyChanged("ID");
}
}
}
private String _Username;
public String Username
{
get { return _Username; }
set
{
if (value != _Username)
{
_Username = value;
OnPropertyChanged();
OnPropertyChanged("Username");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
DataContext:
public class DC
{
public DC()
{
Users = new ObservableCollection<User>();
Users.Clear();
}
public ObservableCollection<User> Users
{
get;
set;
}
public async void LoadData()
{
await Task.Run(() =>
{
// time-consuming load from DB
Users.Add(new User() { Username = "Steve", ID = 1 });
Users.Add(new User() { Username = "Bill", ID = 2 });
});
}
}
App.xaml.cs:
public partial class App : System.Windows.Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
DC dc = new DC();
var view = new ViewMain();
view.DataContext = dc;
view.Show();
dc.LoadData();
}
}
There are 2 controls in the view: RadGridView and RadListBox.
When i bind ItemsSource="{Binding Users}" to RadGridView - it is working.
When i bind ItemsSource="{Binding Users}" to RadListBox - i get exeption:
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread
Why is it not working in this case?
Of course, I can use App.Current.Dispatcher.Invoke, but i don't know if this is a good solution when I want the view to be thread safe? (like not freezeing on adding a lot of items to ObservableCollection).