Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Binding a ViewModel to a Bluetooth Service

$
0
0

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?


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>