M
M
Mozzarella2018-02-18 21:59:23
WPF
Mozzarella, 2018-02-18 21:59:23

How to fix nullreferenceexception in a property?

There is a property in the window

public FormulaViewModel ViewModel
        {
            get
            {
                return DataContext as FormulaViewModel ?? (DataContext = new FormulaViewModel()) as FormulaViewModel;
            }
            set
            {
                DataContext = value;
            }
        }

Further use throws a Null reference exception
private void Parameters_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    {
                        ViewModel.Parameters.Add(e.NewItems[0] as Parameter);
                        break;
                    }
                case NotifyCollectionChangedAction.Remove:
                    {
                        ViewModel.Parameters.Remove(e.OldItems[0] as Parameter);
                        break;
                    }
            }
        }

When debugging, when hovering over a property to see the value, it first throws an exception, and the second time it gives out the created object. How to fix?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DarkByte2015, 2018-02-18
@sfreaky

For God's sake, do not sculpt everything in one line. It doesn't add to the readability. And the problem is most likely just because of this!

if (DataContext is null)
DataContext = new FormulaViewModel()

return DataContext;

A
Alexander, 2018-02-18
@alexr64

Most likely, DataContext == null and an exception is thrown when trying to access the DataContext.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question