简体   繁体   中英

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). I set up a public String in my CS file and did some basic Binding in Xaml like this: <Label Text="{Binding myString}"/>

In my code behind i got an async Task running that refreshes the 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. When i try to assign a value to the String outside of the Task it works fine. 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

2) If yes than you need make sure you set DataContext in your View

3) In your viewModel(VM) you need make property from myString

    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

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

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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