我已经玩了这一天已经有一天了,我就是放弃了 . 基本上,关键是我得到了一个ListBox,其中包含来自数据库的自定义对象(Products) . 填充和排序有效,但不能从所选项目中获取值 .
产品类别:
public class Product {
//properties
public int ID { get; set; }
public String Name { get; set; }
public String Info { get; set; }
public int Stock { get; set; }
public float Price { get; set; }
}
来自frmUser中ListBox的XAML:
<Window.Resources>
<DataTemplate x:Key="listBoxTemplate">
<StackPanel Margin="4">
<DockPanel >
<TextBlock FontWeight="Bold" Text="Product ID: " DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="White" FontSize="13" />
<TextBlock Text="{Binding productId}" Foreground="White" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Naam: " DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="White" FontSize="13"/>
<TextBlock Text="{Binding naam}" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Omschrijving: " DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="White" FontSize="13"/>
<TextBlock Text="{Binding omschrijving}" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Voorraad: " DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="White" FontSize="13"/>
<TextBlock Text="{Binding voorraad}" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Prijs: " DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="White" FontSize="13"/>
<TextBlock Text="{Binding prijs}" />
</DockPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
一旦用户点击填充ListBox,就会完成绑定:
private void fillDataGrid(object sender, RoutedEventArgs e)
{
try
{
BindingOperations.ClearAllBindings(lboxProducts);
dataset = dbWebservice.getDataFromTable(selectedTable);
lboxProducts.ItemsSource = dataset.Tables[selectedTable].DefaultView;
countProducts = 0;
setLabels("0", "0.0");
btnSort.IsEnabled = true;
btnBuy.IsEnabled = true;
}
catch (Exception ex)
{
logger.WriteLine(applicationName, ex.Message);
}
}
现在,一旦用户点击按钮上的“购买”,我希望将所选项目(如果有的话)放入列表或其他任何内容,并读出价格 . 所以我可以使用该值来分配总价格标签 . 如果用户再次点击,请再次从selecteditem中读取价格并将其与上一项相加 . 就这样 . 但我无法在任何情况下得到“存储”在listboxitems中的值,这些值基本上都是“产品”对象 .
在最后,我想使用“已购买和选择”项目将其ID存储回数据库中的tblOrders . 这就是我需要ID和PRICE值的原因 .
我的解决方案是这样的:
ClassObjects.Product product = (ClassObjects.Product)lboxProducts.SelectedItem;
float price = product.Price;
//go on and sum or store the price blabla
但它给出了一个错误,它无法从DataRowView转换为ClassObjects.Product ...
谢谢你的帮助!
2 回答
您可以始终尝试浏览从数据库中检索的行,并为返回的每行创建Product对象并将其放入列表,而不是将itemSource设置为数据视图 . 然后将itemsource设置为此列表 . 然后,当您检索selectedItem时,它将是ClassObjects.Product类型而不是数据视图 .
如果您使用
DataTables
,您将获得这些包装,首先转换为DataRowView
并从那里获取产品(例如使用Item[String]) .