Binding a ViewModel to a Bluetooth Service

DR_BartDR_Bart Member ✭✭
edited April 18 in Xamarin.Forms

Hi,

I am writing a xamarin forms app and I want to bind a property in my ViewModel to the bluetooth adapter state (on/off). In turn, I want to bind a switch in my View to the ViewModel that reflects and can set the bluetooth adapter on and off.

Essentially I want a switch the can set and accurately reflect the state of the bluetooth adapter.

Because it is a xamarin forms app, I am using a dependency service for access to bluetooth on each platform.

The general structure is like this: View (Switch) <-> ViewModel(Property) <-> Interface (Dependency service) <-> Bluetooth Platform (Android)

The View and ViewModel bind to each other without issue, so I will omit that detail.

Here is what I have:

public class BluetoothViewModel : INotifyPropertyChanged
{
    //Ask the container to resolve the service only once.
    private BluetoothServices bluetoothServices;
    protected BluetoothServices BTService => bluetoothServices ?? (bluetoothServices = DependencyService.Get<BluetoothServices>());

    // ... OnPropertyChanged() implementation

    public bool AdapterStatus    // Switch in the View binds to this
    {
        get => BTService.AdapterStatus;
        set
        {
        BTService.AdapterStatus = value;
        OnPropertyChanged();
        }
    }
}



 public interface BluetoothServices   // BluetoothServices interface, used for the bluetooth dependency service
    {
    bool AdapterStatus { get; set; } // Gets/Sets the Bluetooth adapter status
    }



public sealed class BluetoothReceiver : BluetoothServices, INotifyPropertyChanged
{
 private static BluetoothAdapter adapter;

 public bool AdapterStatus
 {
    get => (adapter != null ? adapter.IsEnabled : false);
    set
    {
        if (adapter != null && adapter.IsEnabled != value) // Check that the adapter exists and the status needs to be changed
        {
            switch (value)
            {
                case false:
                    adapter.Disable();  // Disable adapter to reflect switch state
                    break;

                case true:
                    adapter.Enable();   // Enable adapter
                    break;

                default:

                    break;
            }

            OnPropertyChanged();
        }
    }
}

How can I get the change in the adapter status to be propagated to the viewmodel?

Answers

  • ColeXColeX Member, Xamarin Team Xamurai

    What's the problem ? Your code works fine on my side .

Sign In or Register to comment.