如何从c#wpf中动态创建的stackpanel中获取动态创建的标签控件文本

本文关键字:动态 创建 标签 控件 文本 获取 stackpanel c#wpf | 更新日期: 2023-09-27 18:22:12

我的目的是获取列表视图中所选项目的详细信息。listview中的图像和标题是通过使用动态创建的stackpanel来显示的。动态创建的图像文件和标题被添加到stackpanel中。现在我想查看列表视图中所选项目的详细信息吗?能帮我把整理一下吗

// dynamically creating stackpanel in listview
 FileStream stream = new FileStream(item.FullName, FileMode.Open, FileAccess.Read);
 Image i = new Image();
 i.Width = 100;
 i.Height = 100;
 i.Margin = new Thickness(15);
 i.ToolTip = item.Name;
 i.Visibility = Visibility.Visible;
 BitmapImage src = new BitmapImage();
 src.BeginInit();
 src.UriSource = new Uri(SelectedImagePath + "''" + item.Name);
 src.DecodePixelWidth = 100;
 src.DecodePixelHeight = 100;
 //src.StreamSource = stream;
 src.EndInit();
 i.Source = src;
 Label lb = new Label();
 lb.Width = 110;
 lb.Height = 110;
 lb.Content = item.Name;
 StackPanel pn = new StackPanel();
 pn.Orientation = Orientation.Vertical;
 pn.Width = 160;
 pn.Height = 160;
 pn.Children.Add(i);
 pn.Children.Add(lb);
 listView1.Items.Add(pn);
// for retrieving the label control text 
 string fname;
 foreach (StackPanel pan in listView1.SelectedItems)
 {
     var lbl = pan.Children[1].ToString();//not getting in correct format
     MessageBox.Show(lbl.ToString());
 }

提前谢谢。

如何从c#wpf中动态创建的stackpanel中获取动态创建的标签控件文本

尝试将StackPanel.Children项强制转换为正确的类型,而不是调用ToString():

var lbl = (Label)pan.Children[1];   //or use index [0] if you meant the 1st child
MessageBox.Show((string)lbl.Content);