Wpf 无法强制转换类型为';RuntimePropertyInfo';输入';ListBoxItem';

Wpf 无法强制转换类型为';RuntimePropertyInfo';输入';ListBoxItem';,wpf,vb.net,xaml,casting,listbox,Wpf,Vb.net,Xaml,Casting,Listbox,我有一个奇怪的问题,我无法从列表框中获取项目。我甚至尝试使用中的代码,但在我的情况下失败了,并显示一条消息:无法将类型为“System.Reflection.RuntimePropertyInfo”的对象强制转换为类型为“System.Windows.Controls.ListBoxItem”。列表框绑定到来自XAML的颜色 xmlns:sys=“clr命名空间:系统;程序集=mscorlib” System.Windows.Media.Color、PresentationCore、, 版本=3

我有一个奇怪的问题,我无法从列表框中获取项目。我甚至尝试使用中的代码,但在我的情况下失败了,并显示一条消息:无法将类型为“System.Reflection.RuntimePropertyInfo”的对象强制转换为类型为“System.Windows.Controls.ListBoxItem”。列表框绑定到来自XAML的颜色

xmlns:sys=“clr命名空间:系统;程序集=mscorlib”
System.Windows.Media.Color、PresentationCore、,
版本=3.0.0.0,区域性=中性,
PublicKeyToken=31bf3856ad364e35
Private Sub-ListBoxColor\u选择已更改(发件人作为对象_
e作为SelectionChangedEventArgs)处理ListBoxColor.SelectionChanged
作为列表框的发送程序
Dim li作为ListBoxItem
lbsender=CType(发件人,列表框)
li=CType(lbsender.SelectedItem,ListBoxItem)

它在最后一行中断

列表框中的项目是
颜色类的属性。无法将属性强制转换为
ListBoxItem
,因为它不是一个属性

请尝试调用
ListBox.containerformelement(lbsender.SelectedItem)


MSDN来源:

列表框中的项目类型为
System.Reflection.PropertyInfo
。所以你需要这样做:

C#

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
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