MessageBox必须显示元素名称而不是元素类型

时间:2018-05-26 19:09:23

标签: wpf vb.net xaml

XAML

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="430" Width="525">

<Grid>
    <Button x:Name="Button1" Content="Click Me" Width="90" Height="30" VerticalAlignment="Top"/>

    <ListView x:Name="ListView1" SelectionMode="Single" Margin="50">

        <ListViewItem>
            <StackPanel x:Name="THEME_1_">
                <Label Content="THEME 1"/>
                <TextBlock Background="#fff7bdbd"/>
                <TextBlock Background="#d0ff99"/>
                <TextBlock Background="#ffc378"/>
                <TextBlock Background="#fff593"/>
            </StackPanel>
        </ListViewItem>

        <ListViewItem IsSelected="True">
            <StackPanel x:Name="THEME_2_">
                <Label Content="THEME 2"/>
                <TextBlock Background="#bca7dd"/>
                <TextBlock Background="#6dd8d6"/>
                <TextBlock Background="#e086e5"/>
                <TextBlock Background="#ffeab6b6"/>
            </StackPanel>
        </ListViewItem>

        <ListViewItem>
            <StackPanel x:Name="THEME_3_">
                <Label Content="THEME 3"/>
                <TextBlock Background="#ffe9c1"/>
                <TextBlock Background="#d2b6d4"/>
                <TextBlock Background="#ebf2d4"/>
                <TextBlock Background="#f2b8b1"/>
            </StackPanel>
        </ListViewItem>

    </ListView>
</Grid>

</Window>

vb.net

    Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
    For Each obj As Object In LogicalTreeHelper.GetChildren(CType(ListView1.SelectedItem, DependencyObject))
        MessageBox.Show(obj.ToString)
    Next
    End Sub

上述代码效果很好。

当您运行上面的代码并单击Button1时,您将看到MessageBox显示 System.Windows.Controls.StackPanel

我希望MessageBox向我显示 StackPanel名称

1 个答案:

答案 0 :(得分:2)

现在,您在转换为Object类型时所做的一切,它都没有Name属性。您需要做的是检查对象是否属于StackPanel类型,然后转换为该类型以访问其Name属性

    For Each obj As Object In LogicalTreeHelper.GetChildren(CType(ListView1.SelectedItem, DependencyObject))
        If TypeOf obj Is StackPanel Then
            Dim stackPanel As StackPanel = CType(obj, StackPanel)
            MessageBox.Show(stackPanel.Name)
        End If
    Next