亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 ViewModel 異步更新 UI 元素

如何從 ViewModel 異步更新 UI 元素

C#
慕蓋茨4494581 2023-08-20 10:10:14
我在多個表單上使用標簽來顯示從 WCF 服務調用的天氣數據。我希望每分鐘進行一次更新,以顯示更新的天氣數據,而不干擾用戶交互。我收到以下錯誤:“必須在與 DependencyObject 相同的線程上創建 DependencySource。”我有一個用于異步獲取天氣數據的視圖模型,它繼承自 ViewModelBase 來處理屬性更改事件。ViewModel 中的屬性綁定到標簽天氣視圖模型public class WeatherDataVM : ViewModelBase{    private string _windString;    private SolidColorBrush _windState;    private DispatcherTimer _timer;    public WeatherDataVM()    {        _timer = new DispatcherTimer(DispatcherPriority.Render);        _timer.Interval = TimeSpan.FromSeconds(10);        _timer.Tick += async (sender, args) => {await Task.Run(() => GetWindAsync()); };        //_timer.Tick += _timer_Tick;        _timer.Start();        GetWind();    }    private void GetWind()    {        var weatherFromService = Services.Instance.EmptyStackService.GetWeather();        var windSpeed = Convert.ToDouble(weatherFromService.Windspeed);        var maxGust = Convert.ToDouble(weatherFromService.Max_Gust_In_Last_Min);        var windSpeedMPH = Math.Round(windSpeed * 1.15078, 1);        var maxGustMPH = Math.Round(maxGust * 1.15078, 1);        var windString = $"W/S: {windSpeedMPH}({maxGustMPH})";        var windState = new Color();        if (windSpeed >= 40)            windState = Color.FromRgb(255, 64, 64);        else if (windSpeed >= 24)            windState = Color.FromRgb(255, 212, 128);        else            windState = Color.FromRgb(0, 255, 0);        _windState = new SolidColorBrush(windState);        _windString = windString;    }    private async Task GetWindAsync()    {        var weatherFromService = Services.Instance.EmptyStackService.GetWeather();        var windSpeed = Convert.ToDouble(weatherFromService.Windspeed);        var maxGust = Convert.ToDouble(weatherFromService.Max_Gust_In_Last_Min);        var windSpeedMPH = Math.Round(windSpeed * 1.15078, 1);        var maxGustMPH = Math.Round(maxGust * 1.15078, 1);        var windString = $"W/S: {windSpeedMPH}({maxGustMPH})";    }
查看完整描述

1 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

如果凍結后臺線程,則可以在后臺線程上創建畫筆:

var?brush?=?new?SolidColorBrush(windState);
brush.Freeze();
WindState?=?brush;

DispatcherTimer但如果只是Task.Run在事件處理程序中調用,則使用 a 沒有多大意義Tick。

假設您的事件處理程序僅創建畫筆并且不直接操作任何 UI 元素(當然不應該這樣做,因為它是在視圖模型中實現的),您可以使用System.Timer.Timer。它的Elapsed事件在線程池線程上排隊等待執行,您可以在其中查詢服務而不會阻塞 UI。


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 169 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號