无法将“RuntimePropertyInfo”类型的对象强制转换为“ListBoxItem”类型

时间:2013-04-07 00:49:01

标签: wpf vb.net xaml casting listbox

我有这个奇怪的问题,我无法从ListBox中获取项目。我甚至尝试使用this site中的代码,但在我的情况下它失败了:无法将类型为'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)

它打破了最后一行。

2 个答案:

答案 0 :(得分:1)

ListBox中的项目是Colors类的属性。您无法将属性转换为ListBoxItem,因为它不是一个属性。

请尝试拨打ListBox.ContainerFromElement(lbsender.SelectedItem)

MSDN来源:ContainerFromElement

答案 1 :(得分: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