第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何從 ViewModel 異步更新 UI 元素

如何從 ViewModel 異步更新 UI 元素

C#
慕蓋茨4494581 2023-08-20 10:10:14
我在多個表單上使用標(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})";    }
查看完整描述

1 回答

?
阿波羅的戰(zhàn)車

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個贊

如果凍結(jié)后臺線程,則可以在后臺線程上創(chuàng)建畫筆:

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

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

假設(shè)您的事件處理程序僅創(chuàng)建畫筆并且不直接操作任何 UI 元素(當(dāng)然不應(yīng)該這樣做,因?yàn)樗窃谝晥D模型中實(shí)現(xiàn)的),您可以使用System.Timer.Timer。它的Elapsed事件在線程池線程上排隊(duì)等待執(zhí)行,您可以在其中查詢服務(wù)而不會阻塞 UI。


查看完整回答
反對 回復(fù) 2023-08-20
  • 1 回答
  • 0 關(guān)注
  • 166 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號