ObservableCollection addings items

2019-07-17 05:47发布

In my WPF application I have an Observable Collection of Functions

private ObservableCollection<Function> functions = new ObservableCollection<Function>();

I wrote a command for a button to add new functions to the collection: In this case I am adding a polynomial function.

public ICommand AddPolyFuncCommand
{
    get
    {
        return new Command(obj =>
        {
            Function newPolyFunc = new PolyFunction(this.Coefficients);
            functions.Add(newPolyFunc);
            CalculatePoints();
        });
    }
}

However, if I keep adding more functions, all of the latest functions in the collection are overwritten with the function I want to add. For example I have 3 entries, but the functions are all the same (they should be different).

For example, I create a first function. After that I want to add another different function to the collection. It lets me create the "newPolyFunc" properly but if I take a look at the FunctionsCollection at runtime the first value is already overwritten with the function.

public ICommand AddTrigoFuncCommand
    {
        get
        {
            return new Command(obj =>
            {
                this.functions.Add(newTrigoFunc);
                CalculatePoints();
            });
        }
    }

标签: c# wpf mvvm
1条回答
爷的心禁止访问
2楼-- · 2019-07-17 06:28

By writing Function newPolyFunc = new PolyFunction(this.Coefficients); you pass the Reference of the Coefficents and not a new set of Coefficients. You could use LINQ to create a deep copy of the Coefficients or create an empty set and pass them like this:

//Create deep copy and pass them
ObservableCollection<double> newCoefficients = new ObservableCollection<double>(Coefficients.Select(c => c));

//Create empty set
ObservableCollection<double> newCoefficients = new ObservableCollection<double>(Enumerable.Repeat(0d, Amount/Grade));

Important: When you pass a reference you pass a pointer to the instance/object and not a clone/copy. Always be aware if its a reference or value type. For example the newTrigoFunc is an instance and is passed as reference. So the this.functions has now the same reference saved 2 times and not to different instances/objects. When you want to add a new object/instance i suggest you to create a new one with the Constructor like this

//Add new object/instance
this.functions.Add(new TrigonometricFunctionClass(parameters?));
查看更多
登录 后发表回答