c# - Xamarin C# 跨平台和特定于平台的绑定(bind)

标签 c# android xamarin

这是我的情况。

我有一个用 Xamarin 编写的同时支持 Droid 和 iOS 的应用程序。这些项目中的每一个都需要独立于平台的蓝牙 API。因此,我所做的是创建一个与 DependencyService 一起使用的接口(interface)。我需要的字段是蓝牙设备列表……如果我正在为一个平台开发,这就足够简单了。但在这种情况下,我的蓝牙实现在它自己的线程上“检测”设备,所以我不一定可能返回一个 String[] Names..我的解决方案是这样的,我创建了一个类并且在类中有一个 String[ ] 并且由于该类是一个“引用”,我假设我稍后在代码中添加到列表中时,更改将反射(reflect)在我的 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?被添加到我的 ListView 中。 但是,在加载整个 View 后,在我的 MainActivity(又是 Droid 部分)中调用

 bluetoothItems.Set("TEST");

并且“测试”项从未添加到我的列表中!

我是否清楚我要做什么?

欢迎任何帮助。

最佳答案

DependencyService 实现总是 create a new instance .每次调用 Resolve() 时,它要么是一个全局实例,要么是一个新实例。您可以通过设置 DependencyFetchTarget ( see docs ) 来配置行为。

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

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

关于c# - Xamarin C# 跨平台和特定于平台的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383124/

相关文章:

c# - EF Core 与 Postgres 正在生成负主键

c# - 在 C# 上为属性设置默认值

c# - 使用 XSD.exe 为引用类型生成 minOccurs = 1 的不可空字段

android - Android模拟器中的动态地理定位更新?

android - 如何在对话框中处理后退按钮?

android - Xamarin SQLite.NET 通用表查询

c# - 使用 UWP c# 的 gpio 的 raspberry PI 读取值

Android Sqlite IN,NOT IN 语法

c# - 日期选择器 : How to popup datepicker when click on edittext using C# xamarin

c# - 如何在 .NET Core 控制台应用程序中使用 Microsoft.Extensions.DependencyInjection?