代码之家  ›  专栏  ›  技术社区  ›  GrooverFromHolland

UWP ListView绑定错误

  •  0
  • GrooverFromHolland  · 技术社区  · 8 年前

    在我的UWP应用程序主页XAML中,我尝试绑定 ObservableCollection<BluetoothLEDevice> BleDeviceList 到ListView。
    如果我运行我的应用程序,我会得到以下错误:

    System.InvalidcastException:无法将“windows.devices.bluetouth.bluetouthdevice”类型的对象强制转换为“uwpsimpleable exampleWithSomeControls.mainpage”类型。 在UWPsimpleTable中,示例为somecontrols.mainpage.mainpage.obj2_bindings.setdataroot(object newdataroot) 在UWPsimpleTable示例中,包含somecontrols.mainpage.mainpage.obj2_bindings.processbindings(对象项,Int32项索引,Int32阶段,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>  
    

    如果我注释掉行文本块文本..错误消失了,所以我的绑定肯定有问题。

    1 回复  |  直到 8 年前
        1
  •  1
  •   gregkalapos    8 年前

    正如注释中所讨论的,解决方案是将x:datatype从 MainPage BluetoothLEDevice 类。另外, 蓝齿设备 还必须导入类。对于x:bind,您必须定义绑定到的类的类型,在这种情况下,正确的类是 蓝齿设备 .

    因此,这应该是完成工作的代码:

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

    这条线使得 蓝齿设备 在XAML页中可见的类:

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

    This page 描述X:与数据模板绑定(尤其是“datatemplate和X:datatype”部分)。

    推荐文章