3

I am writing WPF application using MVVM. I have ObservableCollection of my items:

public ObservableCollection<VarValue> Values;

public class VarValue: INotifyPropertyChanging, INotifyPropertyChanged
{
    public double value
    {
        get
        {
            return this._value;
        }
        set
        {
            if (this._value != value)
            {
                this.OnvalueChanging(value);
                this.SendPropertyChanging();
                this._value = value;
                this.SendPropertyChanged("value");
                this.OnvalueChanged();
            }
        }
    }
}

which is binded to dataGrid1:

dataGrid1.ItemsSource = Values;

<DataGrid EnableColumnVirtualization="true" EnableRowVirtualization="true" Name="dataGrid1" DockPanel.Dock="Top" AutoGenerateColumns="False" Height="120" Width="Auto" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserResizeRows="False" CanUserSortColumns="False" SelectionUnit="Cell">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate><TextBlock Text='{Binding Values.value}'/></DataTemplate></DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate><TextBox Text='{Binding Values.value, Mode=TwoWay}'/></DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGrid>

When user edits dataGrid1 cell, I need to create new VarValue object, and insert it into existing collection. For example:

  • datagrid contains one cell with value=1
  • user changes it to value=2
  • now in table must be two cells: with 1 and 2 values.

How can i achieve that?

1 Answer 1

1

You could create a wrapper around VarValue and bind it in your grid:

public class VarValueVM : INotifyPropertyChanged
{
    private VarValue _value;
    private ObservableCollection<VarValueVM> _values;

    public VarValueVM(VarValue value, ObservableCollection<VarValueVM> values)
    {
        _value = value;
        _values = values;
    }

    public double value
    {
        get
        {
            return _value.value;
        }
        set
        {
            if (this._value.value != value)
            {
                _values.Add(new VarValueVM(new VarValue() { value = value }, _values));
                this.SendPropertyChanged("value"); //In order to tell the grid that value did not change finally...
            }
        }
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.