Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a listview called "orderDetailsListView" and i also have buttons that each represent a certain product. When that button is pressed, it adds and displays the "Product Name" and "price" of that product into the ListView. However, there is a label below that i want the running total of all products in the listview displayed.

I don't want the total to be displayed via button, as soon as an product is added into the ListView, I want the total to automatically updated with the new total of all products inside of the ListView.

I sadly, haven't got any code to paste as I've literally been trying for the last 11 hours and its got to the point where i've just deleted all lines of code that I've been trying due to NONE of them working.
I'll just paste as much as I can find that is relevant.

This is the XAML code to the listview.
XML
<ListView x:Name="orderDetailsListView" HorizontalAlignment="Left" Height="168" Margin="780,55,0,0" VerticalAlignment="Top" Width="400" Background="#FFBFBFBF">
            <ListView.View>
                <GridView x:Name="orderDetailsGridView">
                    <GridViewColumn Width="280" Header="Product Name"  DisplayMemberBinding="{Binding Path=Name}" />
                    <GridViewColumn Width="60" Header="Price"  DisplayMemberBinding="{Binding Path=Price}"/>
                </GridView>
            </ListView.View>
        </ListView>




further note, Its a WPF not Windows Forms, which means SubItem wont work.


Sorry for lack of code snippets, but I've literally got no where.
Posted
Comments
HKHerron 5-Mar-15 15:02pm    
Try looking at this: http://www.codeproject.com/Articles/54645/WPF-ListView-which-can-do-Sorting-Filtering-Totals

1 solution

This should not be too difficult to set up.


”c#”
//Define a class to store the data. The entities, Name and Price, need to be defined as properties 
//so that they can be bound to controls.
public  class Product
  {
      public string Name { get; set; }

      public double Price { get; set; }


  }

//Define a view model to act as the DataContext for the Window
//The view model needs to have a collection to store the products, a SelectedProduct property and a TotalPrice property.
namespace ListViewSelect
{
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows.Input;
    // Install the following reference using Nuget
    //It will also  install the Prism.SharedIterfaces.dll
    using Microsoft.Practices.Prism.Commands;
    public class ProductsVM : INotifyPropertyChanged
    {
     private ObservableCollection<product> itemsSource;
     public ObservableCollection<product> ItemsSource
        {
            get
            {
                return this.itemsSource;
            }
            set
            {
                this.itemsSource = value;
                this.NotifyPropertyChanged("ItemsSource");
            }
        }
     private Product selectedProduct;

     public Product SelectedProduct
        {
            get
            {
                return this.selectedProduct;
            }

            set
            {
                this.selectedProduct = value;
                this.NotifyPropertyChanged("SelectedProduct");
            }
        }

     private double totalPrice;

     public double TotalPrice
        {
            get
            {
                return this.totalPrice;
            }

            set
            {
                this.totalPrice = value;
                this.NotifyPropertyChanged("TotalPrice");
            }
        }
//There needs to be a Command property that can be bound to the  main window’s ‘Add’ button,
   public ICommand AddProductCommand { get; private set; }

// A PropertyChangedEvent notifies the window when a property changes in the view model 
   public event PropertyChangedEventHandler PropertyChanged;

//This fires the PropertyChanged event
   private void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
             {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }


//The view model’s constructor initialises everything.
   public ProductsVM()
        {
            this.AddProductCommand = new DelegateCommand<object>(this.AddProduct);

            this.itemsSource = new ObservableCollection<product>
            {
                new Product { Name = "A", Price = 1 },
                new Product { Name = "B", Price = 2 },
                new Product { Name = "C", Price = 3 }
            };
           //The view model subscribes to the Collection changed event   
            this.itemsSource.CollectionChanged += this.itemsSource_CollectionChanged;
            this.updateTotalPrice();
        }

//The AddProduct method adds a Product to the collection.
   private void AddProduct(object sender)
        {
            this.ItemsSource.Add(new Product { Name = "Z", Price = 20 });
        }

//The subscription to the Collection changed event of the collection 
//results in the event calling  the itemsSource_CollectionChanged method.

   private void itemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            this.updateTotalPrice();
        }

   private void updateTotalPrice()
        {
            //using Linq
            double total = this.itemsSource.Sum(p => p.Price);
            //using foreach
            // double total =0;
            //foreach (Product p in this.itemsSource)
            //{
            //    total += p.Price;
            //}

            this.TotalPrice = total;
        }
  }
}
//Set the main windows xaml as follows
<window x:class="ListViewSelect.MainWindow" xmlns:x="#unknown">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" 
      xmlns:local="clr-namespace:ListViewSelect" >
    <!--xmlns:local is a reference to the namespace in which the view model is defined-->
    <window.datacontext>
        <local:productsvm xmlns:local="#unknown" />
    </window.datacontext>
    <grid>
        <stackpanel>
            <textblock text="{Binding TotalPrice}" margin="5,0,0,0" fontsize="21.333" fontfamily="Tahoma" fontweight="Bold" />
            <listview itemssource="{Binding ItemsSource}" selecteditem="{Binding SelectedProduct, Mode=TwoWay}" issynchronizedwithcurrentitem="True">
                HorizontalAlignment="Center" Height="168"  VerticalAlignment="Top" Width="400" Background="#FFBFBFBF">
             
                <listview.view>
                    <gridview x:name="orderDetailsGridView">
                        <gridviewcolumn width="280" header="Product Name" displaymemberbinding="{Binding Path=Name}" />
                        <gridviewcolumn width="60" header="Price" displaymemberbinding="{Binding Path=Price}" />
                    </gridview>
                </listview.view>
            </listview>
            <textblock text="{Binding SelectedProduct.Name}" margin="5,0,0,0" fontsize="21.333" fontfamily="Tahoma" fontweight="Bold" />
     <button command="{Binding AddProductCommand}">Add</button>
        </stackpanel>
    </grid>
</window>

</product></object></product></product>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900