型号:
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();
}
}
视图中有2个控件:RadGridView和RadListBox。
当我将ItemsSource =“ {Binding Users}”绑定到RadGridView时,它正在工作。
当我将ItemsSource =“ {Binding Users}”绑定到RadListBox时-我得到了启发:
这种CollectionView不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改
为什么在这种情况下不起作用?
当然,我可以使用App.Current.Dispatcher.Invoke,但是当我希望视图是线程安全的时,我不知道这是否是一个好的解决方案? (如不冻结将大量项目添加到ObservableCollection)。