WPF如何从ListBoxItem内的stackpanel获取值

本文关键字:stackpanel 获取 内的 ListBoxItem WPF | 更新日期: 2023-09-27 18:15:54

我目前正在开发一个WPF应用程序,其中包含一个ListBox和内部ListBoxItemStackPanel和一个ImageLabelStackPanel。所有ListBoxItem都是通过数据库值生成的,并显示在ListBox控件中。但是,当用户选择一个ListBoxItem如何从Label获得一个值,例如?这是我的XAML代码:

<ListBox Name="LIstBProdutos"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         HorizontalAlignment="Left"
         Height="336"
         Margin="39,98,0,0"
         VerticalAlignment="Top"
         Width="358">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True"
                       Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

方法背后的代码

private void BTTProduct_Click(object sender, RoutedEventArgs e) 
{ 
    ListProd.Items.Clear();
    SqlDataReader reader;
    string consulta = "";
    if (CCKBOXFilterProdCat.IsChecked == true)
    {
        var idCategoria = Int32.Parse(((DataRowView)CBBFilterCatProd.SelectedItem)["id"].ToString());
        consulta = "and categoria ='" + idCategoria + "'";
    }
    c.ConsultaSql("select * from produto where nome like '%" + TBXNomeProduto.Text + "%'" + "" + consulta + " ");
    c.NonQuery();
    c.DataSet();
    reader = c.cm.ExecuteReader();
    int nome = 0;
    for (int a = 0; a < c.ds.Tables[0].Rows.Count; a++)
    {
        nome = nome+1;
        ListBoxItem lbi = new ListBoxItem();
        lbi.Width = 100;
        lbi.Height = 152;
        Image img = new Image();
        StackPanel stp = new StackPanel();
        Label lbl = new Label();
        Label lbl2 = new Label();
        stp.Name = "Stack"+ nome.ToString();
        reader.Read();
        string IdImagem = reader["id"].ToString();
        lbl.Content = reader["nome"].ToString();
        lbl2.Content = "R$ " + reader["preco"].ToString();              
        var pa = System.IO.Path.Combine(Environment.CurrentDirectory, "produtos/");
        var uri = new Uri(pa + IdImagem + ".jpg");
        BitmapImage bm = new BitmapImage(uri);
        img.Source = bm;
        stp.Children.Add(img);
        stp.Children.Add(lbl);
        stp.Children.Add(lbl2);
        stp.ToolTip = reader["nome"].ToString() + "'n Somente R$ " + reader["preco"].ToString();
        lbi.Content = stp;                
        ListProd.Items.Add(lbi);                
    }
}

如何获取ListBoxItem的值?

WPF如何从ListBoxItem内的stackpanel获取值

你可以这样做

你可以用你正在获取的数据库字段创建一个类

public class DbRecord
{
    public string ImagePath { get; set; }
    public string nome { get; set; }
    public string preco { get; set; }
}

现在在检查ListBox中是否有记录被选中后,您可以创建我们创建的类的对象,然后获取记录。

if (ListProd.SelectedIndex >= 0)
{
    DbRecord Record = new DbRecord();
    Record = (ListProd.SelectedItem) as DbRecord;
    string nome = Record.nome;
    string preco = Record.preco;
}

在变量中有两个标签的值。