且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在列表视图中显示特定列中所有值的计算总和

更新时间:2022-10-18 13:27:48

这应该设置起来并不太难。

  //  定义一个用于存储数据的类。实体名称和价格需要定义为属性 
// 以便它们可以绑定到控件。
public class 产品
{
public string 名称{ get ; set ; }

public double 价格{获得跨度>; set ; }


}

// 定义一个查看模型以充当窗口的DataContext
// 视图模型需要具有用于存储产品的集合,SelectedProduct属性和TotalPrice属性。
命名空间 ListViewSelect
{
使用 System.Collections.ObjectModel;
使用 System.Collections.Specialized;
使用 System.ComponentModel;
使用 System.Linq;
使用 System.Windows.Input;
// 使用Nuget安装以下参考
// 它还将使用
/ span> Microsoft.Practices.Prism.Commands;
public class ProductsVM:INotifyPropertyChanged
{
private ObservableCollection< product>的ItemsSource;
public ObservableCollection< product> ItemsSource
{
get
{
return this
.itemsSource;
}
set
{
this .itemsSource = ;
this .NotifyPropertyChanged( ItemsSource);
}
}
private Product selectedProduct;

public Product SelectedProduct
{
get
{
return .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);
}
}
// 需要有一个Command属性可以是绑定到主窗口的添加按钮,
public ICommand AddProductCommand { get ; private set ; }

// 当视图模型中的属性发生更改时,PropertyChangedEvent会通知窗口
public event PropertyChangedEventHandler PropertyChanged;

// 这会触发PropertyChanged事件
private void NotifyPropertyChanged( string propertyName)
{
if this .PropertyChanged!= null
{
this .PropertyChanged( this , new
PropertyChangedEventArgs(propertyName));
}
}


// 视图model的构造函数初始化所有内容。
public ProductsVM()
{
.AddProductCommand = new DelegateCommand< object>( this .AddProduct);

.itemsSource = new ObservableCollection< product>
{
new 产品{Name = A,价格= 1 },
new 产品{ Name = B,Price = 2 },
new 产品{Name = C,价格= 3 }
};
// 视图模型订阅集合已更改事件
this .itemsSource.CollectionChanged + = this .itemsSource_CollectionChanged;
this .updateTotalPrice();
}

// AddProduct方法将一个Product添加到集合中。 / span>
private void AddProduct( object 发​​件人)
{
.ItemsSource.Add( new Product {Name = Z,Price = 20 });
}

// 集合的订阅更改了集合的事件
// 导致事件调用itemsSource_CollectionChanged方法。

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

private void updateTotalPrice()
{
// 使用Linq
double total = this .itemsSource.Sum(p = > p.Price) ;
// 使用foreach
// double total = 0;
// foreach(this.itemsSource中的产品p)
// {
// total + = p.Price;
// }

this .TotalPrice = total;
}
}
}
// 设置主窗口xaml如下
< 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 命名空间 的参考,其中视图模型定义的 - >
< 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 = 粗体 />
< listview itemssource = {Binding ItemsSource} selecteditem = {Binding SelectedProduct,Mode = TwoWay} issynchronizedwithcurrentitem = True >
Horizo​​ntalAlignment = 中心高度= 168 VerticalAlignment = Top Width = 400 Background = #FFBFBFBF >

< listview.view>
< gridview x:name = orderDetailsGridView >
< gridviewcolumn width = 280 header = 产品名称 displaymemberbinding = {Binding Path = Name}
/>
< gridviewcolumn width = 60 header = 价格 displaymemberbinding = {Binding Path = Price} />
< / gridview >
< / listview.view >
< / listview >
< textblock text = {Binding SelectedProduct.Name} margin = 5,0,0,0 fontsize = 21.333 fontfamily = Tahoma fontweight = 粗体 />
< button command = {Binding AddProductCommand}>添加< / 按钮 >
< / stackpanel >
< / grid >
< / 窗口 >

< / product > < / object > < / product > < / product &GT; 跨度>


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.

<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.

This should not be too difficult to set up.

//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>