我有这个奇怪的问题,我无法从列表框中获取项目。我甚至试图使用this site中的代码,但是在我的情况下失败并显示一条消息:无法将类型为“System.Reflection.RuntimePropertyInfo”的对象转换为键入“System.Windows.Controls.ListBoxItem”。列表框绑定为来自XAML的颜色。无法投入'RuntimePropertyInfo'类型的对象来键入'ListBoxItem'
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Window.Resources>
<ObjectDataProvider MethodName="GetType"
ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
<ObjectDataProvider.MethodParameters>
<sys:String>System.Windows.Media.Colors, PresentationCore,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35
</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
MethodName="GetProperties" x:Key="colorPropertiesOdp">
</ObjectDataProvider>
</Window.Resources>
<!-- etc -->
<ListBox x:Name="ListBoxColor"
ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Margin="5" Grid.RowSpan="5" SelectedIndex="113">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding Name}" Stroke="Black" Margin="2"
StrokeThickness="1" Height="20" Width="50"/>
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Private Sub ListBoxColor_SelectionChanged(sender As Object, _
e As SelectionChangedEventArgs) Handles ListBoxColor.SelectionChanged
Dim lbsender As ListBox
Dim li As ListBoxItem
lbsender = CType(sender, ListBox)
li = CType(lbsender.SelectedItem, ListBoxItem)
它打破的最后一行。