作者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://www.ptt.cc/bbs/C_Sharp/M.1499231038.A.C11.html
推 lightyen: 也許是同步/非同步的問題 試試Invoke 07/05 14:15
→ b26168: Invoke 就完全不會動了 07/05 14:20
推 lightyan: 話說你有用INotifyPropertyChanged嗎? 07/05 16:07
推 s4300026: backgroundworker, application.doevents 07/05 18:57
推 axray: INotifyPropertyChanged 用了就行了吧 07/06 17:29
推 axray: 剛剛試跑你的sample應該是可以檢查看看binding有沒有bind到 07/06 18:05