许多人建议使用调度程序更新UI线程上的observablecollection。但是我想做这样的事情。怀疑使用这个实现我可以面对什么邪恶?我不想使用调度程序,因为它可以在多线程中造成死锁。
namespace WpfApplication162
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Data();
}
}
public class Data:INotifyPropertyChanged
{
private ObservableCollection<string> nameList;
public ObservableCollection<string> NameList
{
get
{
return this.nameList;
}
set
{
this.nameList = value;
this.RaisePropertyChaged("NameList");
}
}
public ObservableCollection<string> TempList { get; set; }
public Data()
{
NameList = new ObservableCollection<string>();
NameList.Add("Loading");
Action Start = new Action(UpdateAysnc);
IAsyncResult result = Start.BeginInvoke(new AsyncCallback(SetList), null);
}
public void SetList(object param)
{
NameList = TempList;
}
public void UpdateAysnc()
{
TempList = new ObservableCollection<string>();
System.Threading.Thread.Sleep(10000);
for (int i=0;i<10;i++)
{
TempList.Add(i.ToString());
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChaged(string info)
{
if (PropertyChanged!= null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
的Xaml
<Grid>
<ListView ItemsSource="{Binding NameList}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding .}"></Label>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
答案 0 :(得分:0)
试试这个:
public Data()
{
NameList = new ObservableCollection<string>();
NameList.Add("Loading");
UpdateAysnc(results => SetList(results));
}
public void SetList(object param)
{
NameList = TempList;
}
public void UpdateAysnc(Action<ObservableCollection<string>> onUpdateComplete)
{
var tempList = new ObservableCollection<string>();
System.Threading.Thread.Sleep(10000);
for (int i=0;i<10;i++)
{
tempList.Add(i.ToString());
}
onUpdateComplete(tempList);
}