【发布时间】:2020-10-30 16:24:22
【问题描述】:
我正在后台连接我的蓝牙 BLE 设备。所以我需要在后面的代码中获取蓝牙 mac 地址,就像我们在 XAML 中显示 mac 地址一样。
ListView x:Name="lv" ItemSelected="lv_ItemSelected" BackgroundColor="White" SeparatorColor="Aqua">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label TextColor="Black" Text="{Binding NativeDevice.Address}"/>
<Label TextColor="Black" Text="{Binding NativeDevice.Name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
所以在我们的 xaml 中,我能够在 NativeDevice.Address 中获取 mac 地址。所以我需要以同样的方式在我的 xaml.cs 中获取它。我可以按照这种方法获取mac地址
var vailditems = adapter.DiscoveredDevices.Where(i => i.NativeDevice.ToString()
但这不是一个好方法,我需要像我的 xaml 一样在 NativeDevice.Address 中获取 mac 地址。我尝试了这种方法,但它给出的地址为空。
public class NativeDevice
{
public string Name { get; set; }
public string Address { get; set; }
}
NativeDevice V = new NativeDevice();
Baddress = V.Address;
为了您的信息,可以在预定义的 IDevice 接口中访问 mac 地址。所以在 IDevice 接口中我需要访问对象 NativeDevice。这是界面。
public interface IDevice : IDisposable
{
Guid Id { get; }
string Name { get; }
int Rssi { get; }
object NativeDevice { get; }
DeviceState State { get; }
IList<AdvertisementRecord> AdvertisementRecords { get; }
Task<IService> GetServiceAsync(Guid id, CancellationToken cancellationToken = default);
Task<IList<IService>> GetServicesAsync(CancellationToken cancellationToken = default);
Task<bool> UpdateRssiAsync();
}
所以我需要访问接口并在后面的代码中获取 NativeDevice.address。而且我将删除 XAML 部分,因此我也不需要 ListView 的 itemsource 中的 mac 地址。 This is the github plugin 如果您想查看我的完整源代码,我已经实现了我的 BLE 应用程序。这是我访问 BLE 对象的代码。
public IDevice device;
var obj = device.NativeDevice;
IDevice接口的代码在哪里
public interface IDevice : IDisposable
{
Guid Id { get; }
string Name { get; }
Plugin.BLE.Abstractions.Contracts.IDevice.UpdateRssiAsync.
int Rssi { get; }
DeviceState State { get; }
object NativeDevice { get; }
Task<IList<IService>> GetServicesAsync(CancellationToken cancellationToken = default);
Task<int> RequestMtuAsync(int requestValue);
Task<bool> UpdateRssiAsync();
}
我对此一无所知。有什么建议吗?
【问题讨论】:
-
cast it 到正确的类型或use reflection 获取值
标签: c# xamarin.forms bluetooth-lowenergy