我目前正在开发一个包含ListBox
的WPF应用程序,其中ListBoxItem
内有StackPanel
个Image
和Label
在StackPanel
内。所有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
获取价值?
答案 0 :(得分:1)
你可以做这样的事情
您可以使用要获取的数据库字段创建一个类
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;
}
您拥有变量中两个标签的值。