C# 通过绑定填充ListView

C# 通过绑定填充ListView,c#,data-binding,bluetooth,uwp,enumeration,C#,Data Binding,Bluetooth,Uwp,Enumeration,基于,我试图用可用蓝牙设备的列表填充列表视图 但是,虽然我使用的代码似乎拾取了我要列出的设备,但它不会填充列表视图。我相信这是因为我试图错误地绑定数据,但我不确定我做错了什么 我非常感谢你能帮我解决这个问题 XAML C# 使用系统; 使用System.Collections.Generic; 使用System.Collections.ObjectModel; 使用系统组件模型; 使用系统诊断; 使用Windows.Devices.Enumeration; 使用Windows基金会; 使用W

基于,我试图用可用蓝牙设备的列表填充
列表视图

但是,虽然我使用的代码似乎拾取了我要列出的设备,但它不会填充
列表视图
。我相信这是因为我试图错误地绑定数据,但我不确定我做错了什么

我非常感谢你能帮我解决这个问题

XAML


C#

使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用系统组件模型;
使用系统诊断;
使用Windows.Devices.Enumeration;
使用Windows基金会;
使用Windows.UI.Core;
使用Windows.UI.Xaml;
使用Windows.UI.Xaml.Controls;
使用Windows.UI.Xaml.Media.Imaging;
名称空间示例\u Android\u连接
{
公共密封部分类主页面:第页
{
专用DeviceWatcher DeviceWatcher=null;
私有类型deventhandler handleraded=null;
私有类型deventhandler handler updated=null;
私有类型DevenHandler handlerRemoved=null;
私有类型DevenHandler handlerEnumCompleted=null;
私有类型DevenHandler handlerStopped=null;
公共主页()
{
初始化组件();
ResultCollection=新的ObservableCollection();
StartWatcher();
}
公共可见收集结果收集{
得到;
私人设置;
}
私有无效连接按钮\单击(对象发送方,路由目标)
{
Debug.WriteLine(“单击连接”);
}
专用void disconnect按钮\单击(对象发送方,路由目标)
{
Debug.WriteLine(“断开连接”);
}
private void ResultsListView\u SelectionChanged(对象发送方、路由目标方)
{
WriteLine(“结果列表视图选择已更改”);
}
私有void StartWatcher()
{
ResultCollection.Clear();
//获取用户界面选择的设备选择器,然后为以下设备添加附加约束:
//可以配对或已经配对。
//DeviceSelectorInfo DeviceSelectorInfo=“”;/(DeviceSelectorInfo)选择或编辑框。选择编辑项;
//字符串选择器=“(“+deviceSelectorInfo.selector+”)“+”和(System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True或System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)”;
deviceWatcher=DeviceInformation.CreateWatcher(
“系统设备Aep协议:=\”{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\”,
null,//不请求此示例的其他属性
设备信息种类、关联点);
//在启动观察程序之前,为观察程序事件连接处理程序
handlerAdded=新类型DevenHandler(异步(观察者,设备信息)=>
{
//由于集合已绑定到UI元素,因此需要在UI线程上更新集合。
等待Dispatcher.RunAsync(CoreDispatcherPriority.Low,()=>
{
添加(新设备信息显示(设备信息));
Debug.WriteLine(“添加了观察者”);
});
});
deviceWatcher.Added+=handlerAdded;
handlerUpdated=新类型DevenHandler(异步(观察者,设备信息更新)=>
{
//由于集合已绑定到UI元素,因此需要在UI线程上更新集合。
等待Dispatcher.RunAsync(CoreDispatcherPriority.Low,()=>
{
//在集合中找到相应的更新设备信息,并传递更新对象
//到现有设备信息的更新方法。这将自动更新对象
//对我们来说。
Debug.WriteLine(“设备计数:+ResultCollection.Count”);
foreach(设备信息显示结果集合中的设备信息显示)
{
if(DeviceInfo disp.Id==DeviceInfo更新.Id)
{
DeviceInfo.Update(DeviceInfo更新);
//如果正在更新的项目当前处于“选中”状态,则更新配对按钮
DeviceInformation Display SelectedDeviceInformation Disp=(DeviceInformation Display)结果列表视图。SelectedItem;
如果(DeviceInfo=SelectedDeviceInfo)
{
//UpdatePairingButtons();
}
打破
}
}
});
<Page
    x:Class="Sample_Android_Connect.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sample_Android_Connect"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <DataTemplate x:Key="ResultsListViewTemplate">
            <Grid Margin="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*" MinWidth="100"/>
                </Grid.ColumnDefinitions>
                <Border Grid.Column="0" Height="40" Width="40" Margin="5" VerticalAlignment="Top">
                    <Image Source="{Binding Path=GlyphBitmapImage}"
                           Stretch="UniformToFill"/>
                </Border>
                <Border Grid.Column="1" Margin="5">
                    <StackPanel>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Name:" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" TextWrapping="WrapWholeWords"/>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Id:" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding Path=Id}" TextWrapping="Wrap"/>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="CanPair:" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding Path=CanPair}"/>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="IsPaired:" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding Path=IsPaired}"/>
                        </StackPanel>
                    </StackPanel>
                </Border>
            </Grid>
        </DataTemplate>
    </Page.Resources>


    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Margin="10">
            <Grid.RowDefinitions>
                <RowDefinition Height="60" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <RelativePanel Background="#0063B1">
                <TextBlock FontSize="30" Foreground="White" RelativePanel.AlignVerticalCenterWithPanel="True" RelativePanel.AlignHorizontalCenterWithPanel="True" Text="Bluetooth Devices" />
            </RelativePanel>

            <RelativePanel Padding="5" Grid.Row="1" Background="#0078D7">
                <TextBlock Name="connectionStatus" FontSize="16" Foreground="White" Padding="2" FontWeight="Medium" RelativePanel.AlignHorizontalCenterWithPanel="True" Text="Connection Status: Not Connected" />

                <Border BorderBrush="AntiqueWhite" BorderThickness="1" RelativePanel.Below="connectionStatus" Name="discoveredDevices" Width="500" Height="500" RelativePanel.AlignHorizontalCenterWithPanel="True" Margin="10">
                    <ListView x:Name="resultsListView"
                                  ItemTemplate="{StaticResource ResultsListViewTemplate}"
                                  ItemsSource="{Binding Path=ResultCollection}"
                                  SelectionChanged="ResultsListView_SelectionChanged"
                                  Height="500"
                                  Width="500">
                    </ListView>
                </Border>

                <RelativePanel RelativePanel.Below="discoveredDevices" RelativePanel.AlignHorizontalCenterWithPanel="True">
                    <Button Name="connectButton" Content="Connect" Click="ConnectButton_Click" IsEnabled="False"/>
                    <Button Name="disconnectButton" RelativePanel.RightOf="connectButton" Content="Disconnect" Click="DisconnectButton_Click" IsEnabled="False"/>
                </RelativePanel>
            </RelativePanel>
        </Grid>
    </Grid>
</Page>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace Sample_Android_Connect
{
    public sealed partial class MainPage : Page
    {
        private DeviceWatcher deviceWatcher = null;
        private TypedEventHandler<DeviceWatcher, DeviceInformation> handlerAdded = null;
        private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> handlerUpdated = null;
        private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> handlerRemoved = null;
        private TypedEventHandler<DeviceWatcher, Object> handlerEnumCompleted = null;
        private TypedEventHandler<DeviceWatcher, Object> handlerStopped = null;

        public MainPage()
        {
            InitializeComponent();

            ResultCollection = new ObservableCollection<DeviceInformationDisplay>();
            StartWatcher();
        }

        public ObservableCollection<DeviceInformationDisplay> ResultCollection {
            get;
            private set;
        }

        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Connect Clicked");
        }

        private void DisconnectButton_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Disconnect Clicked");
        }

        private void ResultsListView_SelectionChanged(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Results List View Selection Changed");
        }

        private void StartWatcher()
        {
            ResultCollection.Clear();

            // Get the device selector chosen by the UI then add additional constraints for devices that 
            // can be paired or are already paired.
            //DeviceSelectorInfo deviceSelectorInfo = "";//(DeviceSelectorInfo)selectorComboBox.SelectedItem;
            //string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
            deviceWatcher = DeviceInformation.CreateWatcher(
                    "System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"",
                    null, // don't request additional properties for this sample
                    DeviceInformationKind.AssociationEndpoint);

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
                    Debug.WriteLine("Watcher Added");
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    Debug.WriteLine("Device Count: " + ResultCollection.Count);
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);

                            // If the item being updated is currently "selected", then update the pairing buttons
                            DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
                            if (deviceInfoDisp == selectedDeviceInfoDisp)
                            {
                                //UpdatePairingButtons();
                            }
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }
                    Debug.WriteLine("Removed");
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Debug.WriteLine("Completed");
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Debug.WriteLine("Stopped");
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            deviceWatcher.Start();
        }

        public class DeviceInformationDisplay : INotifyPropertyChanged
        {
            private DeviceInformation deviceInfo;

            public DeviceInformationDisplay(DeviceInformation deviceInfoIn)
            {
                deviceInfo = deviceInfoIn;
                UpdateGlyphBitmapImage();
            }

            public DeviceInformationKind Kind {
                get {
                    return deviceInfo.Kind;
                }
            }

            public string Id {
                get {
                    return deviceInfo.Id;
                }
            }

            public string Name {
                get {
                    return deviceInfo.Name;
                }
            }

            public BitmapImage GlyphBitmapImage {
                get;
                private set;
            }

            public bool CanPair {
                get {
                    return deviceInfo.Pairing.CanPair;
                }
            }

            public bool IsPaired {
                get {
                    return deviceInfo.Pairing.IsPaired;
                }
            }

            public IReadOnlyDictionary<string, object> Properties {
                get {
                    return deviceInfo.Properties;
                }
            }

            public DeviceInformation DeviceInformation {
                get {
                    return deviceInfo;
                }

                private set {
                    deviceInfo = value;
                }
            }

            public void Update(DeviceInformationUpdate deviceInfoUpdate)
            {
                deviceInfo.Update(deviceInfoUpdate);

                OnPropertyChanged("Kind");
                OnPropertyChanged("Id");
                OnPropertyChanged("Name");
                OnPropertyChanged("DeviceInformation");
                OnPropertyChanged("CanPair");
                OnPropertyChanged("IsPaired");

                UpdateGlyphBitmapImage();
            }

            private async void UpdateGlyphBitmapImage()
            {
                DeviceThumbnail deviceThumbnail = await deviceInfo.GetGlyphThumbnailAsync();
                BitmapImage glyphBitmapImage = new BitmapImage();
                await glyphBitmapImage.SetSourceAsync(deviceThumbnail);
                GlyphBitmapImage = glyphBitmapImage;
                OnPropertyChanged("GlyphBitmapImage");
            }

            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string name)
            {
                Debug.WriteLine("PropertyChanged");
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}
this.DataContext = this;