I'm currently developing a WPF application that contains a ListBox
and inside it a ListBoxItem
Within a StackPanel
and one Image
and Label
inside StackPanel
. All ListBoxItem are generated through database values and displayed inside ListBox
control. But when user select one ListBoxItem
how to get a value from a Label
for example? This is my XAML code:
<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>
Code Behind Method
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);
}
}
How to get the value from ListBoxItem
?
You can do probably do something like this
You can create a class with your Database Fields you are fetching
public class DbRecord
{
public string ImagePath { get; set; }
public string nome { get; set; }
public string preco { get; set; }
}
Now after checking whether any record is selected in the ListBox you can create the object of the Class we have created and then fetching the Record.
if (ListProd.SelectedIndex >= 0)
{
DbRecord Record = new DbRecord();
Record = (ListProd.SelectedItem) as DbRecord;
string nome = Record.nome;
string preco = Record.preco;
}
You have the values of both the labels in the variables.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.