Observablecollection из интерфейса добавить в просмотр списка через связывание - PullRequest
0 голосов
/ 27 сентября 2018

У меня есть приложение, которое использует плагин Xabre.ble.

Когда приложение сканирует устройства, после обнаружения устройства приложение добавляет его к ObservableCollection, которая является производной от интерфейса.

Я создал шаблон данных в Xaml, который я хочу заполнить, но по какой-то причине я не могу получить правильный BindingContext.

По сути, я хочу добавить объекты устройства к моему ObservableCollection IDevice и получить только имена отдельных устройств в привязывающем тексте, чтобы пользователь мог видеть их в списке * 1009.*

Xaml:

<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>

Cs:

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 из интерфейса, но это явно не разрешено.- причина, по которой я бы предпочел это решение, заключается в том, что пользователю в конечном итоге придется подключиться к устройству из списка, а это означает, что гораздо проще иметь один объект для всех деталей «за кадром».

1 Ответ

0 голосов
/ 27 сентября 2018

Вы должны рефакторинг своего кода, чтобы подход MVVM.

namespace YourNameSpace.ViewModels
{
    public class YourViewModel
    {

        private ObservableCollection<IDevice> devices;
        public ObservableCollection<IDevice> Devices
        {
            get { return devices; }
            set
            {
                devices = value;
            }
        }
        public YourViewModel()
        {
            Devices = new ObservableCollection<IDevice>();
        }
    }
}

В вашем Page.xaml.cs

public partial class YourPage : ContentPage
    {
        public YourPage()
        {
            InitializeComponent();
            BindingContext = new YourViewModel();
        }
    }

    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)
        {
            (YourViewModel)Devices.Add(a.Device);               
            //DeviceName.Add(a.Device.Name);
        }
    };
    adapter.StartScanningForDevicesAsync();
}

Затем в Page.xaml

 <ListView ItemsSource="{Binding Devices}"
              CachingStrategy="RecycleElement">
...