作者b26168 (b26168)
看板C_Sharp
标题[问题] WPF MVVM 在无穷回圈的 thread 中更新UI
时间Wed Jul 5 13:03:56 2017
我有一个一直在 catch 资料的 task
当拿到资料後要马上在 UI 上更新
使用 MVVM binding 了 ObservableCollection 的物件到 ListBox
xaml:
<ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>
code:
private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
get
{
return _displayLogs;
}
}
public Testpro()
{
_displayLogs = new ObservableCollection<string>();
Task.Run(new Action(outputData));
}
private void outputData()
{
string str = "";
while (true)
{
string newString = GetInfoString();
if (string.IsNullOrWhiteSpace(newString) || str == newString)
continue;
str = newString;
Debug.WriteLine(str);
Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
{
DisplayLogs.Add(str);
});
}
}
实际上 Debug.WriteLine 能够 realtime 的跑出结果
但是 BeginInvoke 直到没资料的时候才会一次 show 出全部的结果
而且都是最後一个 str 的值
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.128.199.139
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1499231038.A.C11.html
1F:推 lightyen: 也许是同步/非同步的问题 试试Invoke 07/05 14:15
2F:→ b26168: Invoke 就完全不会动了 07/05 14:20
3F:推 lightyan: 话说你有用INotifyPropertyChanged吗? 07/05 16:07
4F:推 s4300026: backgroundworker, application.doevents 07/05 18:57
5F:推 axray: INotifyPropertyChanged 用了就行了吧 07/06 17:29
6F:推 axray: 刚刚试跑你的sample应该是可以检查看看binding有没有bind到 07/06 18:05