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

问题描述 投票:1回答:1

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名称。

wpf vb.net xaml
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.