【问题标题】:UWP Listview binding errorUWP Listview 绑定错误
【发布时间】:2018-05-27 16:24:07
【问题描述】:

在我的 UWP 应用程序主页 xaml 中,我尝试将 ObservableCollection<BluetoothLEDevice> BleDeviceList 绑定到列表视图。
如果我运行我的应用程序,我会收到以下错误:

System.InvalidCastException:无法将“Windows.Devices.Bluetooth.BluetoothLEDevice”类型的对象转换为“UWPsimpleBLE_exampleWithSomeControls.MainPage”类型。 在 UWPsimpleBLE_exampleWithSomeControls.MainPage.MainPage_obj2_Bindings.SetDataRoot(对象 newDataRoot) 在 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>  

如果我注释掉 TextBlock Text 行。错误消失了,所以我的绑定一定有问题

【问题讨论】:

  • 您设置了 x:DataType="local:MainPage"。这就是为什么错误消息说它无法转换...您是否尝试过 x:DataType 与 BluetoothLEDevice?
  • 这个可能有帮助:docs.microsoft.com/en-us/windows/uwp/data-binding/…(参见“DataTemplate and x:DataType”)
  • @gregkalapos 尝试过,但唯一可能的是应用程序和主页。
  • 您是否在 XAML 页面顶部导入了带有“xmlns:...”的类的命名空间?
  • 您应该导入 Windows.Devices.Bluetooth.BluetoothLEDevice,而不是 MainPage。虽然我不确定直接绑定 BluetoothLEDevice 是否是个好主意......也许只包含 BluetoothAddress 和 ConnectionStatus 的类(......加上你需要的)会更好。但无论如何.. 作为第一次尝试,我建议导入 BluetoothLEDevice 并将 x:DataType 更改为此。然后就可以细化了……

标签: c# xaml uwp


【解决方案1】:

正如 cmets 中所讨论的,解决方案是将 x:DataType 从 MainPage 更改为 BluetoothLEDevice 类。此外,还必须导入 BluetoothLEDevice 类。在 x:Bind 的情况下,您必须定义要绑定的类的类型,在这种情况下,正确的类是 BluetoothLEDevice

所以这应该是完成这项工作的代码:

<DataTemplate x:Key="ListDataTemplate" x:DataType="local:BluetoothLEDevice">

这一行使BluetoothLEDevice 类在 XAML 页面中可见:

xmlns:local="using:Windows.Devices.Bluetooth"

This page 描述 x:Binds 与 DataTemplates(尤其是“DataTemplate 和 x:DataType”部分)。

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 2017-10-30
    • 1970-01-01
    • 2018-02-06
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多