2013-04-07 176 views
1

我有这个奇怪的问题,我无法从列表框中获取项目。我甚至试图使用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) 

它打破的最后一行。

回答

1

在列表框中的项目是System.Reflection.PropertyInfo类型。所以,你需要做这样的事情:

C#

if (ListBoxColor.SelectedItem != null) 
{ 
    var selectedItem = (PropertyInfo)ListBoxColor.SelectedItem; 
    var color = (Color)selectedItem.GetValue(null, null); 
    Debug.WriteLine(color.ToString()); 
} 

VB.NET

If ListBoxColor.SelectedItem IsNot Nothing Then 
    Dim selectedItem As PropertyInfo = _ 
     DirectCast(ListBoxColor.SelectedItem, PropertyInfo) 
    Dim color As Color = DirectCast(selectedItem.GetValue(Nothing, Nothing), Color) 
    Debug.WriteLine(color.ToString()) 
End If 
1

ListBox中的项目是Colors类的属性。你不能将一个属性投射到ListBoxItem,因为它不是一个。

尝试拨打ListBox.ContainerFromElement(lbsender.SelectedItem)来代替。

MSDN来源:ContainerFromElement

相关问题