0

我有一个奇怪的问题,我无法从 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)

它在最后一行中断。

4

2 回答 2

1

您的项目是该类ListBox的属性。Colors您不能将属性转换为 a ListBoxItem,因为它不是一个。

试着打电话ListBox.ContainerFromElement(lbsender.SelectedItem)

MSDN 来源:ContainerFromElement

于 2013-04-07T02:27:03.430 回答
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
于 2013-04-07T07:38:03.447 回答