如何动态更改Textblock

时间:2018-01-29 13:53:19

标签: c# wpf

我是wpf和c#的新手。尝试进行实时通知,我有一个包含来自网页的最新信息的文本块。每隔5分钟我收到新信息,应该显示在文本块上,我已经成功接收到信息,但当我将其设置为textblock的属性时,它没有改变,它仍然显示第一个收到的信息。 我的代码:

    async void GetChanges()
    {
        Rootobject allEarthquakes = await Async();
        int count = allEarthquakes.features.Length;

        LastData.Text = "Последнее землетрясение: \nМагнитуда: " + allEarthquakes.features[count - 1].properties.mag + "\nРасположение: " + allEarthquakes.features[count - 1].properties.place + "\nВремя: " + DateTimeOffset.FromUnixTimeMilliseconds(allEarthquakes.features[count - 1].properties.time) + "\nГлубина: " + allEarthquakes.features[count - 1].geometry.coordinates[2] + "\nID: " + allEarthquakes.features[count - 1].id;


    }
    Task<Rootobject> Async()
    {
        string path = @"C:\data\data.json";
        string json;
        string url = @"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";
        using (WebClient client = new WebClient())
        {
            json = client.DownloadString(url);
        }
        Rootobject allEarthquakes = JsonConvert.DeserializeObject<Rootobject>(json);
        int count = allEarthquakes.features.Length;
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        Directory.CreateDirectory(@"C:\data");
        using (StreamWriter stream = File.CreateText(path))
        {
            stream.Write(json);
        }
        return Task.Run(() =>
            allEarthquakes);
    }

其中,LastData是Textblock

1 个答案:

答案 0 :(得分:0)

如果您更改选项卡时TextBlock会刷新,而不是像您没有实现INotifyPropertyChanged界面那样。通常你会像在xaml中一样绑定TextBlock.Text

<TextBlock Text={Binding UpdateText} />

然后在代码隐藏中使用一些字符串属性UpdateText,请参阅this MSDN article