2017-05-08 66 views
0

我正在開發的應用程序正在使用藍牙設備。 每個這些設備都有一個名稱和幾個服務。我試圖以編程方式向他們展示他們的服務。綁定到一個類中的列表

要做到這一點,我創建了一個包含服務列表的類。當嘗試綁定時,服務列表似乎完全是空的。

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)); 
+0

使用ObservableCollection'的''而不是List'。當你向它添加項目時,List不會通知任何人,所以你不會看到UI創建後添加的任何東西。 'ObservableCollection'確實。如果這不能解決它,你可能會搞錯了。 BluetoothDevices是你的視角模型還是別的?它應該實現'INotifyPropertyChanged'。還要注意保加的正確建議。 –

+0

我想這不會是問題,因爲我創建列表,然後將項目添加到observablecollection。 編輯: 即使嵌套observablecollections它不工作。 –

+0

什麼是observablecollection? 「嵌套的observablecollections」是什麼意思?你是說'BluetoothDevices'是一個ObservableCollection嗎?順便說一下,假設至少有一個關於問題原因的假設是錯誤的 - 否則你不會在這裏尋求幫助。 –

回答

1

改變這樣的綁定。我假設你想要這個內部ListView顯示所有可用的服務。爲此,您必須將Services列表綁定到您的ListViewItemsSource,以便列表中的每個項目都是ListView中的元素。通過使用Text="{Binding}",文本塊直接綁定到集合的每個實例(在這種情況下,string直接綁定到Text)。所以修改你的綁定是這樣的:

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

希望這有助於!

編輯:加解釋結合

+0

這樣做,我以前曾嘗試將它綁定到服務本身,但沒有工作。如果我理解正確,綁定在這是指綁定爲itemssource的對象? –

+0

是''Services'必須綁定到'ItemsSource'才能使ListView正常工作。我還在答覆 – degant

+0

中加了一些解釋,非常感謝,MSDN文檔在這個 –