Sturm
Sturm

Reputation: 4125

Initialialize a property in a command

I have a ViewModel (UserControlViewModel) with a command:

public Command PressMeCommand { get; set; }

As well as:

#region Implementation of INotifyPropertyChanged


    private File _myfile;
    public File MyFile
    {
        get
        {
            return _myfile;
        }
        set
        {
            value = _myfile;
            OnPropertyChanged("MyFile");
        }
    }

Where File is my class with a method called read().

I'm adding to my allMyControls ObservableCollection<UserControlViewModel> with another command bound to a button placed in my MainWindow. The following code is from RootViewModel.cs

private void AddUserControl()
    {
        UserControlViewModel myNewControl = new UserControlViewModel();
        myNewControl.PressMeCommand = new Command(() => OnUserControlPressed(myNewControl ));
        allMyControls.Add(myNewControl );
    }

Finally I'm setting the new Command:

private void OnUserControlPressed(UserControlViewModel item)
        {

            if (item != null)
            {
                item.MyFile.read();
                Num = item.MyFile.channels.Count;
            }
        }

It gives me an error "NullReferenceException was unhandled" when I press the button corresponding to PressMeCommand. My first reaction was, oh, I haven't initilialized MyFile so I moved to this:

private void OnUserControlPressed(UserControlViewModel item)
    {

        if (item != null)
        {
            item.MyFile = new File();
            item.MyFile.read(); //Here is the problem
            Num = item.MyFile.channels.Count;
        }
    }

But the problem persists. Now I'm completely out of ideas. What could it be? How to initialize properly my property MyFile?

Upvotes: 2

Views: 60

Answers (1)

max
max

Reputation: 34427

You've got value = _myfile; in property setter. You need to reverse this of course.

Upvotes: 1

Related Questions