获取ObservableCollection列值的总和

时间:2015-02-19 15:30:16

标签: wpf

如何在更改数据网格列值时将ObservableCollection列值的总和添加到另一个属性, - wpf mvvm patern

1 个答案:

答案 0 :(得分:1)

这是一个解决方案:

的Xaml:

<Window x:Class="Mvvm.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="300" Width="400" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <DataGrid Grid.Row="0" 
                  ItemsSource="{Binding VM.MyList}" 
                  SelectedItem="{Binding VM.MyItem , Mode=TwoWay}"
                  />
        <TextBlock Grid.Row="1" Text="{Binding VM.Sum}"/>
    </Grid>
</Window>

查看模特:

public class MainViewModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    public ObservableCollection<ItemViewModel> MyList { get; set; }

    ItemViewModel _myItem;
    public ItemViewModel MyItem
    {
        get
        {
            return _myItem;
        }
        set
        {
            _myItem = value;
            OnPropertyChanged("MyItem");
            OnPropertyChanged("Sum");
        }
    }

    public int Sum
    { 
        get
        {
            return MyList.Sum(a=>a.Amount);
        }
    }

    public MainViewModel()
    {
        MyList = new ObservableCollection<ItemViewModel>();

        MyList.Add(new ItemViewModel { Amount = 5});
        MyList.Add(new ItemViewModel { Amount = 6});
    }

}

public class ItemViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        int _amount;
        public int Amount
        {
            get
            {
                return _amount;
            }
            set
            {
                _amount = value;
                OnPropertyChanged("Amount");
            }
        }
        //Other properties like Id, transactionDate, ...

    }

背后的主窗口代码:

    public MainViewModel VM { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        VM = new MainViewModel();
        DataContext = this;

    }