2013-05-21 29 views
-2

我有两个ListBox es,SourceDestination。目的地ListBox已由用户选择Items如何总结列表框中的项目?

如何汇总目的地项目ListBox

目的地ListBox有两种数据类型String(说明)和decimal(成本)。 我只想总结成本。这里是XAML代码

<ListBox Height="237" HorizontalAlignment="Left" Margin="44,191,0,0" Name="lstDestination" VerticalAlignment="Top" Width="264" Grid.ColumnSpan="2" ItemsSource="{Binding Source={StaticResource myItemList}}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Vertical"> 
       <DockPanel > 
        <TextBlock FontWeight="Bold" Text="Item:" DockPanel.Dock="Left" Margin="5,0,10,0"/> 
        <TextBlock Text="{Binding Path=Resource}" Foreground="Green" FontWeight="Bold" /> 
        <TextBlock FontWeight="Bold" Text="Cost:" DockPanel.Dock="Left" Margin="5,0,10,0"/> 
        <TextBlock Text="{Binding Path=Cost}" FontWeight="Bold" /> 
       </DockPanel> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

这是我试图总结成本代码:

private decimal SumDLstBox() 
{ 
    decimal totalCost; 
    foreach (var i in lstDestination.SelectedItems) 
    { 
     totalCost+=i.Cost; //Error is thrown here    
    } 
    return totalCost; 
} 
//Data Source to List Box Source 
var items = from r in dc.IResources select r; 
     lstSource.ItemsSource = items; 

他们选择Items他/她需要,我的挑战是获得总的用户选择的项目(已移至ListBox目的地)

+0

'ItemsSource'从哪里来?张贴相关的代码。 –

回答

1

要在绑定的数据进行操作,你应该把它转换为你正在使用的数据类型的列表。例如。

private decimal SumDLstBox() 
{ 
    return lstDestination.SelectedItems.Cast<Foo>().Sum(f => f.Cost); 
} 

其中Foo是您绑定到控件的List的数据类型。

+0

谢谢@Shawn我将代码更正为 return lstDestination.Items – love

0

您的.cs-文件将知道属性lstDestination。您可以使用foreach循环遍历lstDestination中的所有元素。在同一个循环中,您可以将成本加起来。

+0

@love那么,试一下,测试一下,如果你不明白为什么它不起作用,请查看SO上的错误消息以查看是否有人在之前询问过它。如果这些答案不能帮助您,请在您的代码,错误消息和您尝试过的东西上发布问题。这就是这个网站的工作方式。我们不会为您创建应用程序。你在哪里撞墙?你不明白的是什么?你真的必须更清楚,因为我无法猜出你不明白的东西...... – Joetjah

+0

@JoeJah我知道我已经用我试过的代码编辑了这个问题。 – love

+0

那么抛出的错误是''object'不包含'Cost'的定义,并且没有扩展方法'Cost'接受类型'object'的第一个参数“ – love

0

在我看来,你不被lstDestination.SelectedItems迭代而是由lstDestination.Items

相关问题