[問題] WPF MVVM 在無窮迴圈的 thread 中更新UI

看板C_Sharp作者 (b26168)時間7年前 (2017/07/05 13:03), 編輯推噓5(501)
留言6則, 5人參與, 最新討論串1/1
我有一個一直在 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

07/05 14:15, , 1F
也許是同步/非同步的問題 試試Invoke
07/05 14:15, 1F

07/05 14:20, , 2F
Invoke 就完全不會動了
07/05 14:20, 2F

07/05 16:07, , 3F
話說你有用INotifyPropertyChanged嗎?
07/05 16:07, 3F

07/05 18:57, , 4F
backgroundworker, application.doevents
07/05 18:57, 4F

07/06 17:29, , 5F
INotifyPropertyChanged 用了就行了吧
07/06 17:29, 5F

07/06 18:05, , 6F
剛剛試跑你的sample應該是可以檢查看看binding有沒有bind到
07/06 18:05, 6F
文章代碼(AID): #1PN7C-mH (C_Sharp)