Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – WPF/MVVM – Unable to set property value from view

I’m opening a dialog in my view in response to a button click. I have a file class with the filePath property like so:

FileClass.cs

    private string _filePath;

    public string FilePath
    {
        get { return _filePath; }
        set 
        { 
            _filePath = value;
            OnPropertyChanged();
        }
    }

I create an instance in my viewModel:

viewmodel

    public MyFile myFile;
    public ViewModel()
    {
        myFile = new MyFile();
    }

The problem is when I try to use the property in the view:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

            if (openFileDialog.ShowDialog() == true)
            {
                filePath = openFileDialog.FileName;

                (this.DataContext as ViewModel)?.myFile.FilePath = filePath; // error

            }

Why can’t I do this?

>Solution :

If you read the error it’ll tell you that (this.DataContext as ViewModel)?.myFile.FilePath isn’t an l-value. It’s also non-sense.

Use this instead:

((ViewModel)DataContext).myFile.FilePath = filePath;

Of course, your setup breaks both MVVM guidelines and .Net naming and field conventions, but to each his own.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading