将ViewModel绑定到蓝牙服务

时间:2019-04-18 12:01:51

标签: xamarin binding

我正在编写一个xamarin表单应用程序,我想将ViewModel中的属性绑定到蓝牙适配器状态(打开/关闭)。反过来,我想将View中的开关绑定到ViewModel,以反映并可以打开和关闭蓝牙适配器。

基本上我想要一个可以设置并准确反映蓝牙适配器状态的开关。

因为它是一个xamarin表单应用程序,所以我正在使用依赖项服务来访问每个平台上的蓝牙。

一般结构如下: 视图(开关)<-> ViewModel(属性)<->接口(依赖服务)<->蓝牙平台(Android)

View和ViewModel可以毫无问题地相互绑定,因此我将省略该细节。

这是我所拥有的:

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();
            }
        }
    }

如何获取适配器状态的更改以传播到视图模型?

0 个答案:

没有答案