如何让MessageBox显示StackPanel的名称而非元素类型?
获取StackPanel的x:Name属性值
没问题,咱们来调整代码实现你要的效果。现在你的代码点击按钮后显示的是StackPanel的类型名称,要改成显示它的x:Name属性值,只需要对获取到的对象做类型转换,然后读取对应的属性就可以了。
修改后的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)) ' 把对象转换为FrameworkElement(StackPanel继承自这个类),就能访问Name属性 Dim targetPanel As FrameworkElement = TryCast(obj, FrameworkElement) If targetPanel IsNot Nothing Then MessageBox.Show(targetPanel.Name) End If Next End Sub
关键说明
- 原来的
obj.ToString()默认返回的是对象的类型字符串,不是咱们需要的x:Name值; - 用
TryCast做类型转换是安全的做法,能避免类型不匹配时抛出异常; - 转换成功后,直接读取
targetPanel.Name就能拿到XAML里设置的x:Name(比如选中第二项时会显示THEME_2_)。
原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>
内容的提问来源于stack exchange,提问作者user5878985
相关产品推荐
相关产品推荐

