我有一个奇怪的问题,我无法从 ListBox 中获取项目。我什至尝试使用此站点中的代码,但在我的情况下它失败并显示一条消息:无法将类型为“System.Reflection.RuntimePropertyInfo”的对象转换为类型“System.Windows.Controls.ListBoxItem”。ListBox 绑定到 XAML 中的颜色。
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)
它在最后一行中断。