Reputation: 806
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:
How can i achieve that?
Upvotes: 3
Views: 484
Reputation: 3195
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...
}
}
}
}
Upvotes: 1