【发布时间】:2012-03-04 21:12:29
【问题描述】:
我已经玩了 1 天了,我打算放弃它。 基本上重点是我得到了一个包含来自数据库的自定义对象(产品)的列表框。填充和排序有效,但无法从所选项目中获取值。
产品类别:
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>
一旦用户点击填充列表框,绑定就完成了:
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);
}
}
现在,一旦用户单击按钮上的“购买”,我希望将所选项目(如果有的话)放置在列表或其他任何内容中,并读出价格。所以我可以使用该值分配给总价格标签。如果用户再次单击,则再次读取所选项目的价格并将其与上一个项目相加。就这么简单。 但我无法在任何情况下获得“存储”在列表框项中的值,这些值基本上是“产品”对象。
最后,我想使用“购买和选择”项目的 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...
感谢您的帮助!
【问题讨论】: