[英]WPF How to get values from stackpanel inside a ListBoxItem
我目前正在開發一個WPF應用程序,其中包含一個ListBox
並在其中包含一個StackPanel
的ListBoxItem
和一個在StackPanel
Image
和Label
。 所有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
獲取值?
你可以做這樣的事情
您可以使用要獲取的數據庫字段創建一個類
public class DbRecord
{
public string ImagePath { get; set; }
public string nome { get; set; }
public string preco { get; set; }
}
現在,在檢查是否在列表框中選擇了任何記錄之后,您可以創建我們創建的Class對象,然后獲取Record。
if (ListProd.SelectedIndex >= 0)
{
DbRecord Record = new DbRecord();
Record = (ListProd.SelectedItem) as DbRecord;
string nome = Record.nome;
string preco = Record.preco;
}
您在變量中都有兩個標簽的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.