繁体   English   中英

如何在列表中插入项目

[英]How to insert items in a List

在下面的代码中,我将项目从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中的top方法中,由于某种原因,我的displayItems变量始终为null 是否需要一些特殊的方式将项目加载到班级的displayItems列表中?

您无需在添加到DataGrid的每个项目上存储选定项目的整个集合。 您可以从DataGrid本身检索集合,并且可以使用这样的计算属性来实现(例如,您可能需要将System.Linq添加到使用中):

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
}

cmbAddExtras.SelectedItem的类型不是ExtraDisplayItems 它为null或其他类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM