Xamarin C#跨平台和特定于平台的绑定

时间:2018-05-17 03:59:00

标签: c# android xamarin

这是我的情况。

我有一个用Xamarin编写的应用程序,它支持Droid和iOS。每个项目都需要独立于平台的蓝牙API。所以,我所做的是创建一个与DependencyService一起使用的接口。我需要的领域是蓝牙设备列表......如果我正在为一个平台开发,这很简单。但在这种情况下,我的蓝牙实现“检测”它自己的线程上的设备,所以我不一定能够返回一个String [] Names ..我的解决方案就是这个,我创建了一个类,并且在类中有一个String [ ]并且由于该类是一个“引用”,我假设我在代码中稍后添加到列表中的更改将反映在我的DependencyService中...但遗憾的是,不,这不是这种情况.....这里有一些代码对于这种情况。

这是我的班级的定义,我“拥有”我的一系列项目。

namespace ThoughtCastRewrite.BluetoothX
{
    public class BluetoothItems
    {
        public string[] ListBTItems = new string[10];


        public BluetoothItems()
        {

            ListBTItems[2] = "TEST";
            ListBTItems[6] = "WtF?";
        }

        public void Set(string stringToAdd)
        {
            ListBTItems[4] = stringToAdd;


        }
    }
}

这段代码在跨平台项目中

BluetoothItems bluetoothItemList = DependencyService.Get<ISlateBluetoothItems>().IBluetoothTest;
listView.ItemsSource = bluetoothItemList.ListBTItems;

现在这里是Droid代码:

 BluetoothItems bluetoothItems = new BluetoothItems();
 public BluetoothItems IBluetoothTest { get => bluetoothItems; }

好吧,这看起来很明显,但TEST和WtF?被添加到我的列表视图中。 但是,在整个视图加载后,在我的MainActivity(Droid部分)中,我调用了

 bluetoothItems.Set("TEST");

并且“TEST”项目永远不会添加到我的列表中!

我在这里清楚我要做的是什么吗?

欢迎任何帮助。

1 个答案:

答案 0 :(得分:2)

DependencyService实施将始终create a new instance。这是每次调用Resolve()的全局实例或新实例。您可以通过设置DependencyFetchTargetsee docs)来配置行为。

无论您如何配置它,您创建的具体BluetoothItems实例都不是Resolve()将返回的实例。这就是为什么您添加的项目不会成为共享代码中的内容的一部分。

如果您想获得不同的行为并返回预先创建的实例,则开箱即用的解决方案将无效。您必须创建自己的逻辑或使用其中许多其他依赖注入选项之一。例如,您可以尝试SimpleIoC尝试我在许多项目中使用它(它是MvvmLight的一部分)。