2015-07-28 93 views
0

在下面的代码中,我将项目从combobox插入到datagrid中。如何在列表中插入项目

private void cmbAddExtras_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    using (TruckServiceClient TSC = new TruckServiceClient()) 
    { 
     var item = cmbAddExtras.SelectedItem as ExtraDisplayItems; 

     if (item != null) 
     { 
      var displayItem = new List<ExtraDisplayItems> 
      { 
       new ExtraDisplayItems 
       {        
        ItemId = item.ItemId, 
        ItemCode = item.ItemCode, 
        ItemDescription = item.ItemDescription, 
        ItemSellingPrice = item.ItemSellingPrice, 
        displayItems = item.displayItems //Always null? 
       } 
      }; 
      dgAddExtras.Items.Add(item); 
     } 
    } 
    btnRemoveAllExtras.Visibility = Visibility.Visible; 
} 

我在下面我的课,在这里我希望能够访问的项目在不同的方法,并得到总和总我ItemSellingPrice创建一个变量。

我的类:

public class ExtraDisplayItems 
{ 
    public List<ExtraDisplayItems> displayItems; 

    public int ItemId { get; set; }  
    public string ItemCode { get; set; }  
    public string ItemDescription { get; set; }  
    public double? ItemSellingPrice { get; set; } 
} 

现在我的问题是,在我插入的项目到DataGrid中的顶级方法,我displayItems变量始终是出于某种原因。是否有一些特殊的方法需要将这些项目加载到我班的displayItems列表中?

+0

你试过通过实例化displayItems吗? – Karthik

+0

@湍流 - 感谢您的回复! :)我怎么去做这件事?请你给我举个例子吗? – CareTaker22

+0

Here you go 'public ExtraDisplayItems(){this.displayItems = new List ();}' – Karthik

回答

2

您不需要在添加到DataGrid的每个项目上存储所选项目的整个集合。您可以检索从DataGrid本身的集合,你可以这样做,用计算出的属性是这样,例如(您可能需要添加System.Linq您usings):

private IEnumerable<ExtraDisplayItems> SelectedDisplayItems 
{ 
    get 
    { 
     return dgAddExtras.Items.Cast<ExtraDisplayItems>(); 
    } 
} 

这样的话,你可以删除列表从ExtraDisplayItems类。

public class ExtraDisplayItems 
{ 
    public int ItemId { get; set; }  
    public string ItemCode { get; set; }  
    public string ItemDescription { get; set; }  
    public double? ItemSellingPrice { get; set; } 
} 

SelectionChanged方法最终会是这样的:

private void cmbAddExtras_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    // You're not using TSC, so you don't need this either 
    //using (TruckServiceClient TSC = new TruckServiceClient()) 
    //{ 
     var item = cmbAddExtras.SelectedItem as ExtraDisplayItems; 

     if (item != null) 
     { 
      dgAddExtras.Items.Add(item); 
     } 
    //} 
    btnRemoveAllExtras.Visibility = Visibility.Visible; 
} 

而且在需要计算的ItemSellingPrice总和的另一种方法,你只需要使用计算的属性。

private void YourOtherMethod() 
{ 
    // do stuff 

    var sum = SelectedDisplayItems.Sum(item => item.ItemSellingPrice ?? 0); // Since ItemSellingPrice can be null, use 0 instead 

    // do more stuff 
} 
+0

哈哈哈woooow !!!我在这个问题上挣扎了很长时间,现在你给了我答案。它完美的工作!非常感谢你almulo! :D我不得不问的所有问题中的最佳答案。 – CareTaker22

+0

很高兴我可以帮助:) – almulo

0

cmbAddExtras.SelectedItem不是ExtraDisplayItems类型。它是空的或不同的类型

+0

谢谢你的答案格伦,但这仍然给我的'displayItems'值** null **。 – CareTaker22

+0

然后你必须将它的值设置为null。 –