Reputation: 1029
In my UWP app mainpage xaml I try to bind an ObservableCollection<BluetoothLEDevice> BleDeviceList
to a listview.
If I run my app I get the following error:
System.InvalidCastException: Unable to cast object of type 'Windows.Devices.Bluetooth.BluetoothLEDevice' to type 'UWPsimpleBLE_exampleWithSomeControls.MainPage'. at UWPsimpleBLE_exampleWithSomeControls.MainPage.MainPage_obj2_Bindings.SetDataRoot(Object newDataRoot) at UWPsimpleBLE_exampleWithSomeControls.MainPage.MainPage_obj2_Bindings.ProcessBindings(Object item, Int32 itemIndex, Int32 phase, Int32& nextPhase)
<Page.Resources>
<DataTemplate x:Key="ListDataTemplate" x:DataType="local:MainPage">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock Text="{x:Bind Path=BleDevice.Name }" HorizontalAlignment="Center" Width="150" />
<StackPanel Margin="20,20,0,0">
<!--<TextBlock Text="{x:Bind BleDevice.BluetoothAddress.ToString()}" HorizontalAlignment="Left" FontSize="16" />-->
<!--<TextBlock Text="{x:Bind BleDevice.ConnectionStatus}" HorizontalAlignment="Left" FontSize="10" />-->
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
<ListView HorizontalAlignment="Stretch" Height="100" Margin="0,0,0,0"
VerticalAlignment="Top" Background="#FFDED7D7"
BorderBrush="#FFF88686" Foreground="Black"
ItemsSource="{x:Bind BleDeviceList}"
ItemTemplate="{StaticResource ListDataTemplate }">
</ListView>
If i comment out the line TextBlock Text.. The error is gone,so I must be doing something wrong with my binding
Upvotes: 0
Views: 288
Reputation: 3619
As discussed in the comments the solution was to change the x:DataType from MainPage
to BluetoothLEDevice
class. Additionally the BluetoothLEDevice
class also had to be imported. In case of x:Bind you have to define the type of the class that you bind to and in this case the correct class was BluetoothLEDevice
.
So this should be the code which does the job:
<DataTemplate x:Key="ListDataTemplate" x:DataType="local:BluetoothLEDevice">
And this line makes the BluetoothLEDevice
class visible within the XAML page:
xmlns:local="using:Windows.Devices.Bluetooth"
This page describes x:Binds with DataTemplates (especially the "DataTemplate and x:DataType" part).
Upvotes: 1