从列表中检索单个值以用于计算

时间:2019-04-05 20:04:03

标签: c# list uwp

我有点困惑。我对列表进行了硬编码,但是我想从列表中的每个项目中提取一个特定的值(价格或iPrice值)。这样,当在xaml中单击按钮时,它将增加所有内容的总定价。

单击按钮,总价需要增加。我不确定我是否使用错误的术语进行研究,这似乎有点简化。

我尝试检查Price参数,如果该值对应于某个设置值(如10),则只需将10加到定价中,就可以完成此工作,但即使这样做感觉也不对

<GridView Name="mylist" ItemsSource="{x:Bind itemlist}" Margin="0,91,0,0">
    <GridView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel>
                    <TextBlock Text="{Binding ItemName}" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Description}" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Price}" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Button Content="Add" Click="CheckTotal_Click" ></Button>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>    

隐藏代码:

   int Pricing = Model.TotalSpent;
List<Item> itemlist = new List<Item>();
public void Items()
{          
    itemlist.Add(new Item("Coke", "A Fizzy Soft Drink", 15));
    itemlist.Add(new Item("Burger", "A Mouth Watering Mouthfull", 25));
    itemlist.Add(new Item("Chips", "Crunchy Crispy Goodness!", 10));
    itemlist.Add(new Item("Bilton", "Yum Yum", 50));
    itemlist.Add(new Item("Caps", "Show of how much you love us", 80));
}
  void CheckTotal_Click(object sender, RoutedEventArgs e)

        {

            txtTotal.Text = "Total: " + Pricing ;
        }

型号:

public class Item
{
    private string iName;
    private string iDescription;
    private int iPrice;

    public Item(string iName, string iDescription, int iPrice)
    {
        this.iName = iName;
        this.iDescription = iDescription;
        this.iPrice = iPrice;
    }

    public string ItemName
    { 
        get { return iName; }
        set { iName = value; }
    }

    public string Description
    {
        get { return iDescription; }
        set { iDescription = value; }
    }
    public int Price
    {
        get { return iPrice; }
        set { iPrice = value; }
    }
}

前端结果如下:

可乐

碳酸饮料

价格是15

(按钮)

1 个答案:

答案 0 :(得分:1)

 private void mylist_ItemClick(object sender, ItemClickEventArgs e)
        {
            var clickedItem = (Item)e.ClickedItem;
            Pricing += clickedItem.Price;
            var collection = (ObservableCollection<Item>)mylist.ItemsSource;
            int index = collection.IndexOf(clickedItem);



            addtototal();
        }

        public int addtototal()
        {
            Model.TotalSpent = Pricing;
            txtTotal.Text = Pricing.ToString();
            return Pricing;

        }

我放弃了直接尝试访问列表视图中被单击成员的操作,因此我的目的是要获取该“被单击项目”的索引,然后为每个索引设置硬编码的“价格”值,例如(索引== 1)定价+ = 10;

相反,我利用事件args从索引的“项目”中提取一个值。

如果这个解释太恐怖了,我深表歉意。