Bind column value to "sum of 2 other column values"

Sep 30, 2009 at 1:35 PM

Hello,

I have a datagrid with 3 columns and x rows. They are all of type "int". The first two columns have a value. These values
can be inserted/updated by the user. I would like to see in the third column the SUM of the values in column 1 and 2...

But I do not know how to write the binding for this so the datagrid automatically makes the summation of both columns (on each row).

Hope you can help me out.

Regards!
M

Sep 30, 2009 at 6:55 PM

One approach is to write a value convertor which takes in the two values and calculates the third value.   I am assuming that the "SUM" is a view only items and doesn't get saved or pushed into any databound object.

Tracy

Oct 1, 2009 at 2:26 AM
Edited Oct 1, 2009 at 2:27 AM
Another thing you can do is implement the logic in the object you're displaying in the datagrid.  I haven't tested this but it should get you started... you'll need to set the binding to ColumnSum to read only.
 
public class MyClass : INotifyPropertyChanged
{

   public event PropertyChangedEventHandler PropertyChanged;

   private column1;
   private column2;

   public int Column1
   {
      get
      {
         return column1;
      }

      set
      {
         column1 = value;
         OnPropertyChanged("ColumnSum");
      }
   }

   public int Column2
   {
      get
      {
         return column2;
      }

      set
      {
         column2 = value;
         OnPropertyChanged("ColumnSum");
      }
   }

   public int ColumnSum
   {
      get
      {
         return Column1 + Column2;
      }
   }

   private void OnPropertyChanged(string propertyName)
   {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
   }

} 
Oct 1, 2009 at 12:50 PM
Edited Oct 1, 2009 at 1:46 PM

Hello,

I'm interessted in using the Converter solution... I have 2 columns. Each is bound to a BINDING...
Now I try to bind the third column. I need to do this in code...

I'm trying this but that gives me an error:

var column = new DataGridTextColumn { Header = "Sum" };
MultiBinding multiBinding = new MultiBinding();
var col1 = (DataGridTextColumn)dataGrid.Columns[2];
var col2 = (DataGridTextColumn)dataGrid.Columns[3];
multiBinding.Bindings.Add(col1.Binding);
multiBinding.Bindings.Add(col2.Binding);
multiBinding.Converter = MyConverter;
column.Binding = multiBinding; 
dataGrid.Columns.Add(column);

 


But this doesn't seem to work. I always get the error:

Cannot set UpdateSourceTrigger on inner Binding of MultiBinding. Only the default Immediate UpdateSourceTrigger is valid.