將值從C#代碼綁定到WPF UI時遇到問題。我已經了解了線程的基礎知識,并且知道我必須使用Dispatcher來綁定自定義后臺線程中的ui線程。我有一個類似的要求,我想通過每秒點擊nse-stockmarket api來不斷更新我的WPF UI,并相應地執行一些邏輯,以便我可以顯示天氣股價正在上升或下降。以下是我如何嘗試實現此目標的代碼...注意:我什至沒有“ CROSS-Thread”的異常 //globally declared var stockName = ""; //wpf button click private void Button_Click(object sender, RoutedEventArgs e) { stockName = "LUPIN"; new Thread(() => { RunStockParallel(share.Key); Action action = new Action(SetTextBoxValues); }).Start(); } public void RunStockParallel(string stockName){ var count = 0 ; do { HttpWebRequest stocks = null; try { //your logic will be here.. } catch (Exception e) { //throw e; } //It will call the delegate method so that UI can update. Action action = new Action(SetTextBoxValues); stockName = count++; } while (true);} private void SetTextBoxValues() { this.Dispatcher.Invoke(() => { this.text1.Text = stockName; }); }當我使用do-while循環時,它將一直循環直到我終止應用程序。在此do-while循環中,我不斷嘗試通過使用此“ counter ++;”更新Text1文本框來更新WPF ui。但是它沒有按預期工作。需要建議或解決方案。:)
3 回答

米脂
TA貢獻1836條經驗 獲得超3個贊
我得到了一個答案。.我在try catch塊內的RunStockParallel方法中的代碼下面添加了代碼。
HttpWebRequest stocks = null;
try
{
//your logic will be here..
Dispatcher.BeginInvoke(new Action(() =>
{
txtName.Text = stockName;
}), DispatcherPriority.Background);
}
catch (Exception e)
{
//throw e;
}
- 3 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
0/150
提交
取消