Search code examples
xamarinmvvmviewmodel

Xamarin: set labelText with an instance of ViewModel isnt updating UI


I defined a Label in Xaml

<Label Text="{Binding DeviceGuid}"/>

set the BindingContext inside my Page

BindingContext = new BluetoothViewModel();

and wrote the code for the getter and setter in the ViewModel

private string _deviceGuid;
    public string DeviceGuid
    {
        get
        {
            return _deviceGuid;
        }
        set
        {
            if (_deviceGuid != value)
            {
                _deviceGuid = value;
                OnPropertyChanged();
            }
        }
    }

So thats the simple Thing :). The Binding works if I change the value inside the ViewModel. Now here it comes: There are some Backgroundtasks (or just other classes) that, in my opinion, should have Access to that property and if they will write it, the UI should update automatically. I think its bad practice but I dont know how to realise it different. I´ve already tried to create another instance of the viewmodel like

BluetoothViewModel a = new BluetoothViewModel();
a.DeviceGuid = "test";

Its calling the OnPropertyChanged() but isnt updating the UI ... Thanks for your help in advance.


Solution

  • When you do this:

    BluetoothViewModel a = new BluetoothViewModel();
    a.DeviceGuid = "test";
    

    You are creating another instance of the viewmodel that is not the one in your BindingContext.

    Do this instead:

    public BluetoothViewModel viewmodel;
    BindingContext = viewmodel= new BluetoothViewModel();
    

    And then:

    viewmodel.DeviceGuid = "test";