Ron
Ron

Reputation: 175

Binding to a list in a class

for an application i'm developing im working with bluetooth devices. each of these devices has a name and several Services. i am trying to show them, and their services programmatically.

to do this i've created a class containing the list of services. when trying to bind however, the list of services seems completely empty.

XAML:

public class BluetoothDevices
{
    public string Name{ get; set;}
    //public List<Guid> Services { get; set; }
    public List<string> Services { get; set; }
}

XAML:

        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Name}" Width="150" />
                    <ListView ItemsSource="{Binding}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Services}"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

c#:

        adapter.ScanForBroadcasts(async (IBlePeripheral peripheral) =>
        {
            //List<Guid> services = new List<Guid>();
            List<string> services = new List<string>();

            string devicename = peripheral.Advertisement.DeviceName;
            var _services = peripheral.Advertisement.Services;
            var servicedata = peripheral.Advertisement.ServiceData;
            //services = (_services.ToList());


            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                services.Add("i am a string ");
                BluetoothDevices.Add(new BluetoothDevices { Name = devicename, Services = services });
            });
            //BluetoothDevices = new ObservableCollection<BluetoothDevices>(BluetoothDevices.Distinct());
        }, TimeSpan.FromSeconds(30));

Upvotes: 0

Views: 321

Answers (1)

degant
degant

Reputation: 4981

Change the binding like this. I am assuming you want this inner ListView to show all the services available. For this you must bind the Services list to the ItemsSource of your ListView so that each item in the list is an element in the ListView. By using Text="{Binding}", the text block is bound directly to each instance of the collection (in this case the string is directly bound to the Text). So modify your bindings like this:

    <ListView ItemsSource="{Binding Services}">
        <ListView.ItemTemplate>
             <DataTemplate>
                 <TextBlock Text="{Binding}"/>
             </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Hope this helps!

EDIT: Added explanation for binding

Upvotes: 1

Related Questions