2016-05-17 5 views
-1

У меня есть DataGrid, который связан с ObservableCollection<Item>. Когда я изменяю количество элемента, я хотел бы автоматически изменить общее количество элемента. Что Quantity*Cost=TotalC# Изменение других значений в каждый момент что-то изменяется с помощью mvvm

<DataGrid ItemsSource="{Binding Invoices.Items}" AutoGenerateColumns="False"> 
    <DataGridTextColumn Header="Name" Binding="{Binding Name}" /> 
    <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" /> 
    <DataGridTextColumn Header="Cost" Binding="{Binding Cost}" /> 
    <DataGridTextColumn Header="Total" Binding="{Binding Total}" /> 
</DataGrid> 

ViewModel является изменяться просто»

public class ViewModel:BaseClass 
{ 
    public ViewModel() 
    { 
     FillInvoice(); 
    } 

    private Invoice _invoice; 
    public Invoice Invoice 
    { 
     get { return _invoice; } 
     set 
     { 
      if (_invoice!=value) 
      { 
       _invoices = value; 
       OnPropertyChanged(); 
      } 
     } 
    } 

    private void FillInvoice() 
    { 
     var customer = new Customer() {Id=1,Name = "James"}; 
     var invoice = new Invoice() {Customer = customer, Id = 1,CustomerId = 1}; 
     var item = new Item() {Cost = Convert.ToDecimal(12.50),Id = 1,Name = "Item"}; 
     for (int i = 0; i < 10; i++) 
     { 
      invoice.Items.Add(item); 
     } 
     Invoices = invoice; 
    } 
} 

Счет-фактура выглядит следующим образом:

public Invoices() 
{ 
    Items=new ObservableCollection<Item>(); 
} 
public int Id { get; set; } 
public int CustomerId { get; set; } 
public Customer Customer { get; set; } 
public ObservableCollection<Item> Items { get; set; } 

Мой пункт выглядит так:

public class Item:BaseClass 
{ 
    private string _name; 
    private decimal _cost; 
    public int Id { get; set; } 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      if (_name!=value) 
      { 
       _name = value; 
       OnPropertyChanged(); 
      } 
     } 
    } 

    private int _quantity; 
    public int Quantity 
    { 
     get { return _quantity; } 
     set 
     { 
      if (_quantity!=value) 
      { 
       _quantity = value; 
       OnPropertyChanged(); 
      } 
     } 
    } 

    public decimal Cost 
    { 
     get { return _cost; } 
     set 
     { 
      if (_cost!=value) 
      { 
       _cost = value; 
       OnPropertyChanged(); 
      } 
     } 
    } 

    private decimal _total; 

    public decimal Total 
    { 
     get { return _total; } 
     set 
     { 
      if (_total != value) 
      { 
       _total = value; 
       OnPropertyChanged(); 
      } 

     } 
    } 

} 

Что я мышление было объявлено ding обработчик события к элементу Quantity, который рассчитает общее количество для меня, но я не уверен, как это сделать, я попытался добавить.

public ViewModel(){ 
    Invoice.Items.Quantity.PropertyChanged += (s,e) 
    { 
     Total = Cost*Quantity 
    } 
} 



public Item() 
{ 
    Quantity.PropertyChanged += (s,e) 
    { 
     Total = Cost*Quantity 
    } 
} 

но он не скомпилирован на них.

+0

Почему вы не делаете Refreshof Items в Setter предмета, который актуализирован Нравится: private int _quantity; public int Количество { get {return _quantity; } комплект { если (_quantity! = Значение) { _quantity = значение; RefreshSomething(); OnPropertyChanged(); } } } – SeeuD1

+0

Попробуйте следующее: 'public decimal Total {get {return Cost * Quantity; }} '(и' OneWay'). – Jose

ответ

1

Вы можете просто реализовать Всего по рассчитанным имущества, если оно всегда равна стоимости * Количество, поскольку нет необходимости хранить избыточные данные:

public decimal Total 
{ 
    get { return Cost * Quantity; } 
} 

Это должно просто работать, если OnPropertyChanged() без параметров запускает событие изменения свойства/null, которое приведет к повторному проверке всех подписанных свойств.

1

Попробуйте добавить OnPropertyChanged("Total"); к вашему Quantity собственности:

private int _quantity; 
public int Quantity 
{ 
    get { return _quantity; } 
    set 
    { 
     if (_quantity!=value) 
     { 
      _quantity = value; 
      OnPropertyChanged(); 
      Total = Cost*Quantity 
      OnPropertyChanged("Total"); 
     } 
    } 
} 
+0

'Total' не следует устанавливать здесь, но быть полностью рассчитанным, как в ответе Бена Джексона. –

0

Вы могли бы код, написанный в вашей собственности, как так:

private decimal _total; 
private int _quantity; 
private decimal _cost 

public decimal Quantity 
{ 
    get { return _quantity; } 
    set 
    { 
     _quantity = value; 
     Total = _quantity * _cost; 
    } 
} 

public decimal Total 
{ 
    get { return _total; } 
    set 
    { 
     if (_total != value) 
     { 
      _total = value; 
      OnPropertyChanged(); 
     } 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^