0
我目前正在開發一個包含ListBox
WPF應用程序內部,裏面一個ListBoxItem
在一個StackPanel
和一個Image
和Label
內StackPanel
從StackPanel的值。所有ListBoxItem都是通過數據庫值生成並顯示在ListBox
控件內部。但是當用戶選擇一個ListBoxItem
如何從Label
獲得一個值?這是我的XAML代碼:WPF如何獲得一個ListBoxItem的
<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
價值?
[如果您首先使用_databinding_,則問題消失](https://msdn.microsoft.com/en-us/library/ff798384.aspx) – MickyD
現在我創建一個如下方法:'if( LIstBProdutos.SelectedItem!= null) { ListBoxItem lbi = LIstBProdutos.SelectedItem as ListBoxItem; StackPanel sp = lbi.Content as StackPanel; 的foreach(在sp.Children的UIElement UI) { 如果(UI是標籤) { MessageBox.Show( 「」 + UI); } }'但我有兩個標籤,我只需要獲得第一個標籤。 –