我正在使用MVVM编写WPF应用程序。我有我的物品的ObservableCollection:

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();
            }
        }
    }
}


绑定到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>


当用户编辑dataGrid1单元格时,我需要创建新的VarValue对象,并将其插入现有集合中。例如:


datagrid包含一个值为1的单元格
用户将其更改为value = 2
现在表中必须有两个单元格:具有1和2的值。


我该如何实现?

最佳答案

您可以围绕VarValue创建包装器并将其绑定到网格中:

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...
            }
        }
    }
}

10-07 23:26