我在多個表單上使用標(biāo)簽來顯示從 WCF 服務(wù)調(diào)用的天氣數(shù)據(jù)。我希望每分鐘進(jìn)行一次更新,以顯示更新的天氣數(shù)據(jù),而不干擾用戶交互。我收到以下錯誤:“必須在與 DependencyObject 相同的線程上創(chuàng)建 DependencySource。”我有一個用于異步獲取天氣數(shù)據(jù)的視圖模型,它繼承自 ViewModelBase 來處理屬性更改事件。ViewModel 中的屬性綁定到標(biāo)簽天氣視圖模型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})"; }
如何從 ViewModel 異步更新 UI 元素
慕蓋茨4494581
2023-08-20 10:10:14