Binding to a DependencyService?

Hi All,

I have a switch. I want to bind the switch state (enabled/disabled) to the state of the device's Bluetooth adapter.
This should be a two way binding, where the switch can toggle the Bluetooth adapter and vice versa.

e.g. When the app starts, the switch should mirror the state of the Bluetooth adapter.
If the switch is toggled, the Bluetooth adapter should mirror the state of the switch.

I have implemented a messy version of this where I use a dependency service to check the state of the adapter when the page is created and then call a another dependency service when the switch is toggled.

Is there a simpler way to just set a binding which allows platform specific calls to get/set the state of the adapter?

Thanks!

Best Answer

  • NicolasKrierNicolasKrier FR ✭✭✭
    edited October 2018 Accepted Answer

    Hi,
    You can bind to a property

    public bool IsBluetoothEnabled
    {
    get => _bluetoothServiceGetByDependencyService.IsBluetoothActivated ;
    set
    {
    _bluetoothServiceGetByDependencyService.IsBluetoothActivated = value;
    //or _bluetoothServiceGetByDependencyService.SetBluetoothState(value);
    }
    }

Answers

  • NicolasKrierNicolasKrier FRMember ✭✭✭
    edited October 2018 Accepted Answer

    Hi,
    You can bind to a property

    public bool IsBluetoothEnabled
    {
    get => _bluetoothServiceGetByDependencyService.IsBluetoothActivated ;
    set
    {
    _bluetoothServiceGetByDependencyService.IsBluetoothActivated = value;
    //or _bluetoothServiceGetByDependencyService.SetBluetoothState(value);
    }
    }

  • DR_BartDR_Bart Member ✭✭

    Yes this worked. Thanks!

    The code I used was the following:

    public bool BTAdapterStatus // gets and sets the Bluetooth adapter status (enabled/disabled)
    {
    get
    {
    return DependencyService.Get().CheckAdapterStatus();
    }
    set
    {
    DependencyService.Get().ToggleAdapter(value);
    }
    }

  • NicolasKrierNicolasKrier FRMember ✭✭✭
    edited October 2018

    @DR_Bart Cool !

    Let me suggest one thing.

    add this code : (let's say your interface for this service is called IAdapterService)

    private IAdapterService _adapterService;
    public IAdapterService AdapterService => _adapterService?? (_adapterService= DependencyService.Get<IAdapterService >());
    
    public bool BTAdapterStatus // gets and sets the Bluetooth adapter status (enabled/disabled)
    {
    get
    {
    return AdapterService.CheckAdapterStatus();
    }
    set
    {
    AdapterService.ToggleAdapter(value);
    }
    }
    

    Thus you only ask the container to resolve the service only once.

Sign In or Register to comment.