简体   繁体   English

将label.Text绑定到从Xamarin中的异步任务更新的字符串

[英]Binding a label.Text to a String that gets updated from async task in Xamarin

So i'm having a Monitor Page in Xamarin where i need values to be refreshed every second (the values obtained from a TcpClient). 所以我在Xamarin中有一个Monitor Page,在其中我需要每秒刷新一次值(从TcpClient获得的值)。 I set up a public String in my CS file and did some basic Binding in Xaml like this: <Label Text="{Binding myString}"/> 我在CS文件中设置了一个公共String,并在Xaml中进行了一些基本的绑定,如下所示: <Label Text="{Binding myString}"/>

In my code behind i got an async Task running that refreshes the myString . 在后面的代码中,我运行了一个异步任务,该任务刷新了myString The task looks something like this: 该任务看起来像这样:

protected async Task syncDisplay(){
            while(true){
                //TcpClient going on, getting some values
                myString = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            }
        }

And then i'm just creating a new Thread where i run the Task. 然后我只是在运行任务的地方创建一个新线程。 That's all. 就这样。 The problem is that no value gets updated to my UI. 问题是没有值更新到我的UI。 When i try to assign a value to the String outside of the Task it works fine. 当我尝试为Task外部的String赋值时,它可以正常工作。 I am sure i'm missing something essential here but i don't really know what. 我确定我在这里遗漏了一些必不可少的东西,但我真的不知道是什么。

Thanks in advance 提前致谢

1) are you using MVVM in your apprication 1)您是否在应用程序中使用MVVM

2) If yes than you need make sure you set DataContext in your View 2)如果需要,请确保在View设置了DataContext

3) In your viewModel(VM) you need make property from myString 3)在您的viewModel(VM)中,您需要myString make属性

    private string _myString;
    public string MyString
    {
        get => _myString;
        set
        {
            _myString = value;
            NotifyPropertyChanged(() => MyString);
        }
    }

4) All code that couse UI update MUST be in UI Thread, like this 4)所有导致UI更新的代码必须位于UI Thread中,像这样

protected async Task syncDisplay(){
        while(true){
            //TcpClient going on, getting some values
        Device.BeginInvokeOnMainThread(()=>MyString = System.Text.Encoding.ASCII.GetString(data, 0, bytes));

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM