当应用程序扫描设备时,一旦发现设备,应用程序就会将其附加到从接口派生的observeCollection。
基本上,我想要实现的是将设备对象添加到我的
ObservableCollection
IDevice
,并在bindingcontext中获取单个设备的名称,以便用户在listview中看到
<ListView x:Name="deviceList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<local:IconView Grid.Row="0" Grid.Column="0" Source="BLE.png" Foreground="#3b5998" WidthRequest="30" HeightRequest="30"/>
<Label Grid.Row="1" Text="{Binding DeviceName}" TextColor="Teal"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
反恐精英:
public ObservableCollection<IDevice> Devices { get; set; }
IAdapter adapter = CrossBluetoothLE.Current.Adapter;
public ObservableCollection<string> DeviceName { get; set; }
public MainPage()
{
//Instantiate observable collection
Devices = new ObservableCollection<IDevice>();
DeviceName = new ObservableCollection<string>();
//Appending peripherals to list
BindingContext = DeviceName;
deviceList.ItemsSource = BindingContext;
Content = deviceList;
Refreshcmd();
}
public void Refreshcmd()
{
//DeviceDiscovered is an event, when it discovers a device, we fire the eventhandler
adapter.DeviceDiscovered += (s, a) =>
{
if (a.Device.Name != null)
{
Devices.Add(a.Device);
DeviceName.Add(a.Device.Name);
}
};
adapter.StartScanningForDevicesAsync();
}
如您所见,我尝试创建一个对象,该对象包含一个仅包含IDevice名称的字符串。但是,它并没有附加到我的数据绑定中
DeviceName
此外,我不太喜欢这个解决方案,因为我更希望能够访问
Devices.Name
但这显然是不允许的。
-我更喜欢这种解决方案的原因是,用户最终必须连接到列表中的设备,这意味着拥有一个对象来处理所有“幕后”细节要容易得多。